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

nameOfString[0]

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

谢谢你的帮助!


当前回答

Swift 3更新

replaceRange函数现在是replaceSubrange

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

其他回答

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ž"

全部小写。小写()

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

全部大写。uppercase ()

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())
    }
}

在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"