Craigt Craigt - 9 months ago 58
Objective-C Question

Insert or split string at uppercase letters objective-c

What would be the most efficient way to convert a string like "ThisStringIsJoined" to "This String Is Joined" in objective-c?

I receive strings like this from a web service thats out of my control and I would like to present the data to the user, so I would just like to tidy it up a bit by adding spaces infront of each uppercase word. The strings are always formatted with each word beginning in an uppercase letter.

I'm quite new to objective-c so cant really figure this one out.



One way of achieving this is as follows:

NSString *string = @"ThisStringIsJoined";
NSRegularExpression *regexp = [NSRegularExpression 
NSString *newString = [regexp 
    range:NSMakeRange(0, string.length) 
    withTemplate:@"$1 $2"];
NSLog(@"Changed '%@' -> '%@'", string, newString);

The output in this case would be:

'ThisStringIsJoined' -> 'This String Is Joined'

You might want to tweak the regular expression to you own needs. You might want to make this into a category on NSString.