NSString: Camel case <=> Snake case
Some NSString
helper methods to easily translate between camel case and snake case. Note: This could be handled with NSRegularExpression
as well, but I wanted to provide this route first:
+ (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];
}
Written by Paris Xavier Pinkney
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Xcode
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#