Skip to content →

iOS: Split a string at case change

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;


@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];


Published in news


Leave a Reply

Your email address will not be published. Required fields are marked *