Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

bilboa

macrumors regular
Jan 16, 2008
213
1
Code:
NSString *str = @"ThisIsCamelCase";
NSCharacterSet *cs = [NSCharacterSet uppercaseLetterCharacterSet];
NSArray *words = [str componentsSeparatedByCharactersInSet:cs];
This almost does what you want. The problem with it is that [NSString componentsSeparatedByCharactersInSet:] removes the separator characters from the result, so you end up with ("is", "s", "amel", "ase"). So you just need to write a version of componentsSeparatedByCharactersInSet: which doesn't remove the separator characters. Since I'm bored I wrote the function. Note that this code ignores the possibility of composed characters.

Code:
NSArray *splitCamelCaseString(NSString *str)
{
    NSCharacterSet *cs = [NSCharacterSet uppercaseLetterCharacterSet];
    NSMutableArray *result = [[NSMutableArray new] autorelease];
    if ([str length] == 0)
        return result;
    
    NSRange wordMatch, endMatch;
    wordMatch.location = 0;
    endMatch = [str rangeOfCharacterFromSet:cs 
                                    options:0 
                                      range:NSMakeRange(1, [str length] - 1)];
    while (endMatch.location != NSNotFound) {
        wordMatch.length = endMatch.location - wordMatch.location;
        [result addObject:[str substringWithRange:wordMatch]];
        wordMatch.location = endMatch.location;
        endMatch = [str rangeOfCharacterFromSet:cs 
                                        options:0 
                                          range:NSMakeRange(wordMatch.location + 1, 
                                                            [str length] - wordMatch.location - 1)];
    }
    
    // add last word
    wordMatch.length = [str length] - wordMatch.location;
    [result addObject:[str substringWithRange:wordMatch]];
    return result;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.