iOS 驼峰命名法与蛇形式(带下划线)的字符串互相转换

下划线字符串转驼峰

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

你可能感兴趣的:(iOS 驼峰命名法与蛇形式(带下划线)的字符串互相转换)