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

nameOfString[0]

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

谢谢你的帮助!


当前回答

下面是我一小步一小步完成的方法,类似于@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)
}

其他回答

斯威夫特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())
    }
}

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

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 3更新

replaceRange函数现在是replaceSubrange

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