下划线字符串转驼峰
- (NSString *)getCamelCaseFromSnakeCase {
NSMutableString *str = [NSMutableString stringWithString:self];
while ([str containsString:@"_"]) {
NSRange range = [str rangeOfString:@"_"];
if (range.location + 1 < [str length]) {
char c = [str characterAtIndex:range.location+1];
[str replaceCharactersInRange:NSMakeRange(range.location, range.length+1) withString:[[NSString stringWithFormat:@"%c",c] uppercaseString]];
}
}
NSLog(@"===== %@", str);
return str;
}
驼峰字符串转下划线
/**
驼峰转下划线
*/
- (NSString *)getSnakeCaseFromCamelCase {
NSMutableString *str = [NSMutableString stringWithString:self];
while ([self isExistUppercaseString:str].length != 0) {
NSString *upperString = [self isExistUppercaseString:str];
NSRange range = [str rangeOfString:upperString];
char c = [str characterAtIndex:range.location];
[str replaceCharactersInRange:NSMakeRange(range.location, range.length) withString:[[NSString stringWithFormat:@"_%c",c] lowercaseString]];
}
NSLog(@"===== %@", str);
return str;
}
/**
判断是否还存在大写字母
*/
- (NSString *)isExistUppercaseString:(NSString *)str {
const char *ch = [str cStringUsingEncoding:NSASCIIStringEncoding];
NSString *result = @"";
for (int i = 0; i < str.length; i++) {
int asciiCode = [str characterAtIndex:i];
if (asciiCode >= 65 && asciiCode <= 90) {
result = [NSString stringWithFormat:@"%c", ch[i]];
return result;
}
}
return result;
}
网友评论