Last Updated: February 25, 2016
·
2.998K
· dracoli

Split a CamelCase string into separate words

Objective: Split a CameCase string such as `iLikeNames' into separate words ("I Like Names").

So I was looking for a way to do this online but found nothing. There was some recommendations on using regex to do it but I thought that was way to messy for such a simple tasks.

Therefore I spent some time writing my own implementation and this is what I came up with. It is tested and passed all my tests. Although the code is a bit long but it gets the job done. There might be a cleaner way to do this so any suggestions are welcome:

This is to be used as a category for NSString.

- (NSString *)splitOnCapital
{
  // Make a index of uppercase characters
  NSRange upcaseRange = NSMakeRange('A', 26);
  NSIndexSet *upcaseSet = [NSIndexSet     indexSetWithIndexesInRange:upcaseRange];

  // Split our camecase word
  NSMutableString *result = [NSMutableString string];
  NSMutableString *oneWord = [NSMutableString string];
  for (int i = 0; i < self.length; i++) {
    char oneChar = [self characterAtIndex:i];
    if ([upcaseSet containsIndex:oneChar]) {
      // Found a uppercase char, now save previous word
      if (result.length == 0) {
        // First word, no space in beginning
        [result appendFormat:@"%@", [oneWord capitalizedString]];
      }else {
        [result appendFormat:@" %@", oneWord];
      }

      // Clear previous word for new word
      oneWord = [NSMutableString string];
    }

    [oneWord appendFormat:@"%c", oneChar];
  }

  // Add last word
  if (oneWord.length > 0) {
    [result appendFormat:@" %@", oneWord];
  }

  return result;
}