Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'?

like image 216
Evolve Avatar asked Jan 04 '11 00:01

Evolve


2 Answers

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);
like image 119
webstersx Avatar answered Oct 11 '22 12:10

webstersx


Here's a simpler Swift version. I've chucked it into an extension

extension String {

    func stringFromCamelCase() -> String {
        var string = self
        string = string.stringByReplacingOccurrencesOfString("([a-z])([A-Z])", withString: "$1 $2", options: NSStringCompareOptions.RegularExpressionSearch, range: Range<String.Index>(start: string.startIndex, end: string.endIndex))
        string.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return string
    }

}

Usage:

var str = "helloWorld"
str = str.stringFromCamelCase()
like image 38
Stephen Radford Avatar answered Oct 11 '22 10:10

Stephen Radford