How do I convert an NSString from CamelCase to TitleCase, 'playerName' into 'Player Name'?

Evolve picture Evolve · Jan 4, 2011 · Viewed 9.1k times · Source

I'm looking for the easiest way to convert a string from camelback format to Title Case format.

How do I change 'playerName' into 'Player Name'?

Answer

webstersx picture webstersx · Mar 21, 2013
NSString *str = @"playerName";
NSMutableString *str2 = [NSMutableString string];

for (NSInteger i=0; i<str.length; i++){
    NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
    if ([ch rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]].location != NSNotFound) {
        [str2 appendString:@" "];
    }
    [str2 appendString:ch];
}
NSLog(@"%@", str2.capitalizedString);