Skip to content

Instantly share code, notes, and snippets.

@pxpgraphics
Created November 18, 2014 19:43
Show Gist options
  • Save pxpgraphics/225d0549980ed14f893d to your computer and use it in GitHub Desktop.
Save pxpgraphics/225d0549980ed14f893d to your computer and use it in GitHub Desktop.
Helper methods to translate snake case into camel case and vice versa.
+ (NSString *)stringByReplacingSnakeCaseWithCamelCase:(NSString *)string
{
NSArray *components = [string componentsSeparatedByString:@"_"];
NSMutableString *camelCaseString = [NSMutableString string];
[components enumerateObjectsUsingBlock:^(NSString *component, NSUInteger idx, BOOL *stop) {
[camelCaseString appendString:(idx == 0 ? component : [component capitalizedString])];
if (idx > 0) {
[camelCaseString appendString:[component capitalizedString]];
} else {
[camelCaseString appendString:component];
}
}];
return [camelCaseString copy];
}
+ (NSString *)stringByReplacingCamelCaseWithSnakeCase:(NSString *)string
{
NSUInteger index = 1;
NSMutableString *snakeCaseString = [NSMutableString stringWithString:string];
NSUInteger length = snakeCaseString.length;
NSCharacterSet *characterSet = [NSCharacterSet uppercaseLetterCharacterSet];
while (index < length) {
if ([characterSet characterIsMember:[snakeCaseString characterAtIndex:index]]) {
[snakeCaseString insertString:@"_" atIndex:index];
index++;
}
index++;
}
return [snakeCaseString copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment