Created
June 22, 2013 13:12
-
-
Save eienf/5840816 to your computer and use it in GitHub Desktop.
convert camel case to/from snake case in Objective-C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
NSString *toCamelCase(NSString *s) | |
{ | |
return [[[s capitalizedString] componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet]] componentsJoinedByString:@""]; | |
} | |
NSString *splitOnCapital(NSString *s) { | |
NSRange upcaseRange = NSMakeRange('A', 26); | |
NSRange numberRange = NSMakeRange('0', 10); | |
NSIndexSet *upcaseSet = [NSIndexSet indexSetWithIndexesInRange:upcaseRange]; | |
NSIndexSet *numberSet = [NSIndexSet indexSetWithIndexesInRange:numberRange]; | |
NSMutableString *result = [NSMutableString string]; | |
NSMutableString *oneWord = [NSMutableString string]; | |
BOOL prevLetterIsUc = NO; | |
for (int i = 0; i < s.length; i++) { | |
char oneChar = [s characterAtIndex:i]; | |
if ([upcaseSet containsIndex:oneChar]||[numberSet containsIndex:oneChar]) { | |
if ( prevLetterIsUc ) { | |
} else { | |
if (result.length == 0) { | |
[result appendFormat:@"%@", [oneWord lowercaseString]]; | |
}else { | |
[result appendFormat:@"_%@", [oneWord lowercaseString]]; | |
} | |
oneWord = [NSMutableString string]; | |
} | |
prevLetterIsUc = YES; | |
} else { | |
prevLetterIsUc = NO; | |
} | |
[oneWord appendFormat:@"%c", oneChar]; | |
} | |
if (oneWord.length > 0) { | |
[result appendFormat:@"_%@", [oneWord lowercaseString]]; | |
} | |
return result; | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSLog(@"%@", toCamelCase(@"test Example one")); | |
NSLog(@"%@", toCamelCase(@"example Two ")); | |
NSLog(@"%@", toCamelCase(@"is_this_3Rd_EXAMPLE?..")); | |
NSLog(@"%@", splitOnCapital(@"TestExampleOne")); | |
NSLog(@"%@", splitOnCapital(@"ExampleTwo ")); | |
NSLog(@"%@", splitOnCapital(@"IsThis3RdEXAMPLE?..")); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment