Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or split string at uppercase letters objective-c

Tags:

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.

Thanks

like image 455
Craigt Avatar asked Sep 06 '11 15:09

Craigt


2 Answers

One way of achieving this is as follows:

NSString *string = @"ThisStringIsJoined";
NSRegularExpression *regexp = [NSRegularExpression 
    regularExpressionWithPattern:@"([a-z])([A-Z])" 
    options:0 
    error:NULL];
NSString *newString = [regexp 
    stringByReplacingMatchesInString:string 
    options:0 
    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.

like image 90
aLevelOfIndirection Avatar answered Sep 29 '22 18:09

aLevelOfIndirection


NSRegularExpressions are the way to go, but as trivia, NSCharacterSet can also be useful:

- (NSString *)splitString:(NSString *)inputString {

    int index = 1;
    NSMutableString* mutableInputString = [NSMutableString stringWithString:inputString];

    while (index < mutableInputString.length) {

        if ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[mutableInputString characterAtIndex:index]]) {
            [mutableInputString insertString:@" " atIndex:index];
            index++;
        }
        index++;
    }

    return [NSString stringWithString:mutableInputString];
}
like image 24
Matt Wilding Avatar answered Sep 29 '22 19:09

Matt Wilding