Last active
September 28, 2016 20:53
-
-
Save giacaglia/28e2af2d64451f62c72bf10d648a67b2 to your computer and use it in GitHub Desktop.
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
- (nonnull NSString *)camelCaseToSnakeCaseString | |
{ | |
if ([self length] == 0) { | |
return @""; | |
} | |
NSMutableString *output = [NSMutableString string]; | |
NSCharacterSet *digitSet = [NSCharacterSet decimalDigitCharacterSet]; | |
NSCharacterSet *uppercaseSet = [NSCharacterSet uppercaseLetterCharacterSet]; | |
NSCharacterSet *lowercaseSet = [NSCharacterSet lowercaseLetterCharacterSet]; | |
for (NSInteger idx = 0; idx < [self length]; idx += 1) { | |
unichar c = [self characterAtIndex:idx]; | |
// if it's the last one then just append lowercase of character | |
if (idx == [self length] - 1) { | |
if ([uppercaseSet characterIsMember:c]) { | |
[output appendFormat:@"%@", [[NSString stringWithCharacters:&c length:1] lowercaseString]]; | |
} | |
else { | |
[output appendFormat:@"%C", c]; | |
} | |
continue; | |
} | |
unichar nextC = [self characterAtIndex:(idx+1)]; | |
// this logic finds the boundaries between lowercase/uppercase/digits and lets the string be split accordingly. | |
if ([lowercaseSet characterIsMember:c] && [uppercaseSet characterIsMember:nextC]) { | |
[output appendFormat:@"%@_", [[NSString stringWithCharacters:&c length:1] lowercaseString]]; | |
} | |
else if ([lowercaseSet characterIsMember:c] && [digitSet characterIsMember:nextC]) { | |
[output appendFormat:@"%@_", [[NSString stringWithCharacters:&c length:1] lowercaseString]]; | |
} | |
else if ([digitSet characterIsMember:c] && [uppercaseSet characterIsMember:nextC]) { | |
[output appendFormat:@"%@_", [[NSString stringWithCharacters:&c length:1] lowercaseString]]; | |
} | |
else { | |
// Append lowercase of character | |
if ([uppercaseSet characterIsMember:c]) { | |
[output appendFormat:@"%@", [[NSString stringWithCharacters:&c length:1] lowercaseString]]; | |
} | |
else { | |
[output appendFormat:@"%C", c]; | |
} | |
} | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment