Craigt Craigt - 1 year ago 94
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.


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download