Last Updated: February 25, 2016
·
1.045K
· pxpgraphics

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];
}