驼峰下划线互转

驼峰下划线互转

/**
 * 将驼峰风格替换为下划线风格
 */
public static String camelhumpToUnderline(String str) {
    final int size;
    final char[] chars;
    final StringBuilder sb = new StringBuilder(
            (size = (chars = str.toCharArray()).length) * 3 / 2 + 1);
    char c;
    for (int i = 0; i < size; i++) {
        c = chars[i];
        if (isUppercaseAlpha(c)) {
            sb.append('_').append(toLowerAscii(c));
        } else {
            sb.append(c);
        }
    }
    return sb.charAt(0) == '_' ? sb.substring(1) : sb.toString();
}

/**
 * 将下划线风格替换为驼峰风格
 */
public static String underlineToCamelhump(String str) {
    Matcher matcher = UNDERLINE_TO_CAMELHUMP_PATTERN.matcher(str);
    StringBuilder builder = new StringBuilder(str);
    for (int i = 0; matcher.find(); i++) {
        builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
    }
    if (Character.isUpperCase(builder.charAt(0))) {
        builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
    }
    return builder.toString();
}

 

posted @ 2022-09-21 09:30  VipSoft  阅读(106)  评论(0编辑  收藏  举报