How to capitalize the first word of the sentence in Objective-C?

后端 未结 9 538
青春惊慌失措
青春惊慌失措 2021-01-30 08:54

I\'ve already found how to capitalize all words of the sentence, but not the first word only.

NSString *txt =@\"hi my friends!\"
[txt capitalizedString];
         


        
9条回答
  •  遥遥无期
    2021-01-30 09:32

    I know the question asks specifically for an Objective C answer, however here is a solution for Swift 2.0:

    let txt = "hi my friends!"
    var sentencecaseString = ""
    
    for (index, character) in txt.characters.enumerate() {
        if 0 == index {
            sentencecaseString += String(character).uppercaseString
        } else {
            sentencecaseString.append(character)
        }
    }
    

    Or as an extension:

    func sentencecaseString() -> String {
        var sentencecaseString = ""
        for (index, character) in self.characters.enumerate() {
            if 0 == index {
                sentencecaseString += String(character).uppercaseString
            } else {
                sentencecaseString.append(character)
            }
        }
        return sentencecaseString
    }
    

提交回复
热议问题