Created
October 3, 2012 18:07
-
-
Save jdriscoll/3828685 to your computer and use it in GitHub Desktop.
NSString+Inflections
This file contains 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
// Inspired by suggestion to use NSScanner: http://stackoverflow.com/questions/1918972/camelcase-to-underscores-and-back-in-objective-c | |
#import "NSString+Inflections.h" | |
@implementation NSString (Inflections) | |
- (NSString *)underscore | |
{ | |
NSScanner *scanner = [NSScanner scannerWithString:self]; | |
scanner.caseSensitive = YES; | |
NSCharacterSet *uppercase = [NSCharacterSet uppercaseLetterCharacterSet]; | |
NSCharacterSet *lowercase = [NSCharacterSet lowercaseLetterCharacterSet]; | |
NSString *buffer = nil; | |
NSMutableString *output = [NSMutableString string]; | |
while (scanner.isAtEnd == NO) { | |
if ([scanner scanCharactersFromSet:uppercase intoString:&buffer]) { | |
[output appendString:[buffer lowercaseString]]; | |
} | |
if ([scanner scanCharactersFromSet:lowercase intoString:&buffer]) { | |
[output appendString:buffer]; | |
if (!scanner.isAtEnd) | |
[output appendString:@"_"]; | |
} | |
} | |
return [NSString stringWithString:output]; | |
} | |
- (NSString *)camelcase | |
{ | |
NSArray *components = [self componentsSeparatedByString:@"_"]; | |
NSMutableString *output = [NSMutableString string]; | |
for (NSUInteger i = 0; i < components.count; i++) { | |
if (i == 0) { | |
[output appendString:components[i]]; | |
} else { | |
[output appendString:[components[i] capitalizedString]]; | |
} | |
} | |
return [NSString stringWithString:output]; | |
} | |
- (NSString *)classify | |
{ | |
return [[self camelcase] capitalizedString]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty nice, but the method does not work, since -capitalizedString converts a string like "camelCase" to "Camelcase"
This should fix it: