Skip to content

Instantly share code, notes, and snippets.

@jdriscoll
Created October 3, 2012 18:07
Show Gist options
  • Save jdriscoll/3828685 to your computer and use it in GitHub Desktop.
Save jdriscoll/3828685 to your computer and use it in GitHub Desktop.
NSString+Inflections
// 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
@brototyp
Copy link

Pretty nice, but the method does not work, since -capitalizedString converts a string like "camelCase" to "Camelcase"
This should fix it:

- (NSString *)classify
{
    NSString *camelcase = [self camelcase];
    return [camelcase stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[camelcase substringWithRange:NSMakeRange(0, 1)] uppercaseString]];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment