Skip to content

Instantly share code, notes, and snippets.

@DracoLi
Created August 5, 2012 08:32
Show Gist options
  • Save DracoLi/3262933 to your computer and use it in GitHub Desktop.
Save DracoLi/3262933 to your computer and use it in GitHub Desktop.
Split a camelcase string into separate words
//
// NSString+SplitOnCapital.h
//
// Created by Draco Li on 2012-08-04.
// Copyright (c) 2012 Draco Li. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (SplitOnCapital)
- (NSString *)splitOnCapital;
@end
//
// NSString+SplitOnCapital.m
//
// Created by Draco Li on 2012-08-04.
// Copyright (c) 2012 Draco Li. All rights reserved.
//
#import "NSString+SplitOnCapital.h"
@implementation NSString (SplitOnCapital)
- (NSString *)splitOnCapital
{
// Make a index of uppercase character
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;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment