Created
November 18, 2014 19:43
-
-
Save pxpgraphics/225d0549980ed14f893d to your computer and use it in GitHub Desktop.
Helper methods to translate snake case into camel case and vice versa.
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
+ (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