-
-
Save zwf/8593920 to your computer and use it in GitHub Desktop.
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