View Full Version : Easy way to split strings like ThisIsCamelCase?
detz
Aug 14, 2008, 11:51 AM
Is there a quick way I can split that up?
ChrisBrightwell
Aug 14, 2008, 03:23 PM
Is there a quick way I can split that up?
Scan for capital letters.
bilboa
Aug 14, 2008, 03:30 PM
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.
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;
}
detz
Aug 15, 2008, 07:29 AM
Works great, thanks man.
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.