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

wal picture wal · Mar 12, 2010 · Viewed 24.4k times · Source

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];

I don't want to change to lower case and capitalize the first char. I'd like to capitalize the first word only without change the others.

Answer

Johan Kool picture Johan Kool · Mar 12, 2010

Here is another go at it:

NSString *txt = @"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];

For Swift language:

txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)