Easy way to split strings like ThisIsCamelCase?

Discussion in 'iOS Programming' started by detz, Aug 14, 2008.

  1. detz macrumors 65816

    Joined:
    Jun 29, 2007
  2. ChrisBrightwell macrumors 68020

    ChrisBrightwell

    Joined:
    Apr 5, 2004
    Location:
    Huntsville, AL
    #2
    Scan for capital letters.
     
  3. bilboa macrumors regular

    Joined:
    Jan 16, 2008
    #3
    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;
    }
    
     
  4. detz thread starter macrumors 65816

    Joined:
    Jun 29, 2007

Share This Page