October 19, 2011

I was looking to split a string on case changes today, and googling that problem didn’t turn up much. Here’s my implementation via a category. I hope it helps someone.

@interface NSString (Extensions)

- (NSString*) spacify;

@end

@implementation NSString (Extensions)

- (NSString*) spacify
{
    // ignore irrelevant strings
    if (self.length < 1)
        return self;

    NSMutableString* result = [NSMutableString stringWithString:self];

    // create a range starting after the first character
    NSRange range;
    range.location = 1;
    range.length = [self length] - 1;

    // match any uppercase character
    NSRegularExpression* r = [NSRegularExpression regularExpressionWithPattern: @"[A-Z]"
                                                                       options: 0
                                                                         error: nil];

    // replace matches with the match preceded by a space
    [r replaceMatchesInString: result
                      options: 0
                        range: range
                 withTemplate: @" $0"];

    return [NSString stringWithString:result];
}

@end

Reply