我正在尝试制作一个自动更正系统,当用户输入一个大写字母的单词时,自动更正不起作用。为了解决这个问题,我复制了键入的字符串,应用了. lowercasestring,然后比较它们。如果字符串确实输入错误,则应该更正单词。然而,取而代之的单词都是小写的。所以我需要对第一个字母应用. uppercasestring。我本来觉得我可以用

nameOfString[0]

但这显然行不通。我怎么能得到字符串的第一个字母大写,然后能够打印完整的字符串与第一个字母大写?

谢谢你的帮助!


包括与API准则一致的突变和非突变版本。

斯威夫特3:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst())
        return first + other
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

斯威夫特4:

extension String {
    func capitalizingFirstLetter() -> String {
      return prefix(1).uppercased() + self.lowercased().dropFirst()
    }

    mutating func capitalizeFirstLetter() {
      self = self.capitalizingFirstLetter()
    }
}

extension String {
    func firstCharacterUpperCase() -> String? {
        let lowercaseString = self.lowercaseString

        return lowercaseString.stringByReplacingCharactersInRange(lowercaseString.startIndex...lowercaseString.startIndex, withString: String(lowercaseString[lowercaseString.startIndex]).uppercaseString)
    }
}

let x = "heLLo"
let m = x.firstCharacterUpperCase()

对于Swift 5:

extension String {
    func firstCharacterUpperCase() -> String? {
        guard !isEmpty else { return nil }
        let lowerCasedString = self.lowercased()
        return lowerCasedString.replacingCharacters(in: lowerCasedString.startIndex...lowerCasedString.startIndex, with: String(lowerCasedString[lowerCasedString.startIndex]).uppercased())
    }
}

我用柯尔斯泰因斯解得到了第一个复制的字符。这将大写第一个字符,不会看到双字符:

var s: String = "hello world"
s = prefix(s, 1).capitalizedString + suffix(s, countElements(s) - 1)

我不知道它的效率是高还是低,我只知道它给了我想要的结果。


下面是我一小步一小步完成的方法,类似于@Kirsteins。

func capitalizedPhrase(phrase:String) -> String {
    let firstCharIndex = advance(phrase.startIndex, 1)
    let firstChar = phrase.substringToIndex(firstCharIndex).uppercaseString
    let firstCharRange = phrase.startIndex..<firstCharIndex
    return phrase.stringByReplacingCharactersInRange(firstCharRange, withString: firstChar)
}

Swift 5.1或更高版本

extension StringProtocol {
    var firstUppercased: String { prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { prefix(1).capitalized + dropFirst() }
}

斯威夫特5

extension StringProtocol {
    var firstUppercased: String { return prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { return prefix(1).capitalized + dropFirst() }
}

"Swift".first  // "S"
"Swift".last   // "t"
"hello world!!!".firstUppercased  // "Hello world!!!"

"DŽ".firstCapitalized   // "Dž"
"Dž".firstCapitalized   // "Dž"
"dž".firstCapitalized   // "Dž"

Leonardo Savio Dabus:

我想大多数用例是获得适当的套管:

import Foundation

extension String {

    var toProper:String {
        var result = lowercaseString
        result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return result
    }
}

我的解决方案:

func firstCharacterUppercaseString(string: String) -> String {
    var str = string as NSString
    let firstUppercaseCharacter = str.substringToIndex(1).uppercaseString
    let firstUppercaseCharacterString = str.stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: firstUppercaseCharacter)
    return firstUppercaseCharacterString
}

结合上面的答案,我写了一个小扩展,大写每个单词的第一个字母(因为这是我正在寻找的,并认为其他人可以使用它)。

我谦卑地提出:

extension String {
    var wordCaps:String {
        let listOfWords:[String] = self.componentsSeparatedByString(" ")
        var returnString: String = ""
        for word in listOfWords {
            if word != "" {
                var capWord = word.lowercaseString as String
                capWord.replaceRange(startIndex...startIndex, with: String(capWord[capWord.startIndex]).uppercaseString)
                returnString = returnString + capWord + " "
            }
        }
        if returnString.hasSuffix(" ") {
            returnString.removeAtIndex(returnString.endIndex.predecessor())
        }
        return returnString
    }
}

Swift 2.0(单行):

String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())

func helperCapitalizeFirstLetter(stringToBeCapd:String)->String{
    let capString = stringToBeCapd.substringFromIndex(stringToBeCapd.startIndex).capitalizedString
    return capString
}

也工作,只是传递你的字符串,并得到一个大写的回来。


extension String {
    var lowercased:String {
        var result = Array<Character>(self.characters);
        if let first = result.first { result[0] = Character(String(first).uppercaseString) }
        return String(result)
    }
}

在Swift 3.0中(这比公认的答案更快更安全):

extension String {
    func firstCharacterUpperCase() -> String {
        if let firstCharacter = characters.first {
            return replacingCharacters(in: startIndex..<index(after: startIndex), with: String(firstCharacter).uppercased())
        }
        return ""
    }
}

nameOfString。大写是不行的,句子里的每个单词都要大写


斯威夫特3.0

“Hello World”

nameOfString.capitalized

或“HELLO WORLD”

nameOfString.uppercased

字符串中的第一个字符大写

extension String {
    var capitalizeFirst: String {
        if self.characters.count == 0 {
            return self

        return String(self[self.startIndex]).capitalized + String(self.characters.dropFirst())
    }
}

Swift 3更新

replaceRange函数现在是replaceSubrange

nameOfString.replaceSubrange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalized)

Swift 3 (xcode 8.3.3)

大写字符串的所有首字符

let str = "your string"
let capStr = str.capitalized

//Your String

全部大写

let str = "your string"
let upStr = str.uppercased()

//YOUR STRING

字符串的第一个字符只能大写

 var str = "your string"
 let capStr = String(str.characters.prefix(1)).uppercased() + String(str.characters.dropFirst())

//Your string

我更喜欢这个版本,它是从另一个答案中清理出来的版本:

extension String {
  var capitalizedFirst: String {
    let characters = self.characters
    if let first = characters.first {
      return String(first).uppercased() + 
             String(characters.dropFirst())
    }
    return self
  }
}

它努力通过只评估自我来提高效率。字符一次,然后使用一致的形式创建子字符串。


斯威夫特4.0

string.capitalized(with: nil)

or

string.capitalized

但是,每个单词的首字母都要大写

苹果公司的文档:

A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators. Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings. See the getLineStart(_:end:contentsEnd:for:) method for additional information.


Swift 4 (Xcode 9.1)

extension String {
    var capEachWord: String {
        return self.split(separator: " ").map { word in
            return String([word.startIndex]).uppercased() + word.lowercased().dropFirst()
        }.joined(separator: " ")
    }
}

对于单词使用中的第一个字符。在swift中大写,对于整个单词使用。大写()


如果你想大写字符串的每个字,你可以使用这个扩展

Swift 4 Xcode 9.2

extension String {
    var wordUppercased: String {
        var aryOfWord = self.split(separator: " ")
        aryOfWord =  aryOfWord.map({String($0.first!).uppercased() + $0.dropFirst()})
        return aryOfWord.joined(separator: " ")
    }
}

Used

print("simple text example".wordUppercased) //output:: "Simple Text Example"

如果你的字符串都是大写,那么下面的方法将工作

labelTitle.text = remarks?.lowercased().firstUppercased

这个扩展将帮助你

extension StringProtocol {
    var firstUppercased: String {
        guard let first = first else { return "" }
        return String(first).uppercased() + dropFirst()
    }
}

斯威夫特4

func firstCharacterUpperCase() -> String {
        if self.count == 0 { return self }
        return prefix(1).uppercased() + dropFirst().lowercased()
    }

从Swift 3你可以很容易地使用 文本框。autocapitalizationType = uitextautocapitalizationtype .sentence


下面是Swift 5的一个版本,如果第一个字母已经是大写,或者没有大小写的概念,使用Unicode标量属性API来保释:

extension String {
  func firstLetterUppercased() -> String {
    guard let first = first, first.isLowercase else { return self }
    return String(first).uppercased() + dropFirst()
  }
}

在swift 5中

https://www.hackingwithswift.com/example-code/strings/how-to-capitalize-the-first-letter-of-a-string

extension String {
    func capitalizingFirstLetter() -> String {
        return prefix(1).capitalized + dropFirst()
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

和你的绳子一起使用

let test = "the rain in Spain"
print(test.capitalizingFirstLetter())

对于swift 5,你可以简单地这样做:

为字符串创建扩展:

extension String {
    var firstUppercased: String {
        let firstChar = self.first?.uppercased() ?? ""
        return firstChar + self.dropFirst()
    }
}

then

yourString.firstUppercased

样本:"abc" -> "abc"


在viewDidLoad()方法中添加这一行。

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words

编辑:这不再适用于文本,现在只支持输入字段。

以防有人以同样的问题结束这里关于SwiftUI:

// Mystring is here
TextField("mystring is here")
   .autocapitalization(.sentences)


// Mystring Is Here
Text("mystring is here")
   .autocapitalization(.words)

我假设您想要将整个单词串的第一个单词大写。例如:“我的猫很胖,我的脂肪很松弛”应该返回“我的猫很胖,我的脂肪很松弛”。

Swift 5:

为此,您可以导入Foundation,然后使用大写的属性。例子:

import Foundation
var x = "my cat is fat, and my fat is flabby"
print(x.capitalized)  //prints "My Cat Is Fat, And My Fat Is Flabby"

如果你想成为一个纯粹主义者,不导入基础,那么你可以创建一个字符串扩展。

extension String {
    func capitalize() -> String {
        let arr = self.split(separator: " ").map{String($0)}
        var result = [String]()
        for element in arr {
            result.append(String(element.uppercased().first ?? " ") + element.suffix(element.count-1))
        }
        return result.joined(separator: " ")
    }
}

然后你可以这样使用:

var x = "my cat is fat, and my fat is flabby"
print(x.capitalize()) //prints "My Cat Is Fat, And My Fat Is Flabby"

全部小写。小写()

首字母大写,其他字母小写,大写

全部大写。uppercase ()