java转换驼峰命名与蛇形命名的几种方式

方式一: 

 /**
     * 蛇形命名 转 驼峰
     * @param str 待转换的蛇形命名字符串
     * @return  转换后的驼峰式命名
     */
    public static String camelize(String str){
        if(isBlank(str))
            return str;
        Pattern pattern = Pattern.compile("(.*)_(\\w)(.*)");
        Matcher matcher = pattern.matcher(str);
        if(matcher.find()){
            return camelize(matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3));
        }else{
            return str;
        }
    }

    /**
     * 驼峰命名 转 蛇形命名
     * @param camelCaseStr  驼峰式命名
     * @return  转换后的蛇形命名
     */
    public static String decamelize(String camelCaseStr){
        return isBlank(camelCaseStr) ? camelCaseStr : camelCaseStr.replaceAll("[A-Z]", "_$0").toLowerCase();
    }

    /**
     * 字符串是否为空 spring工程直接使用StringUtils中的该方法即可
     * @param cs   待检查的字符串
     * @return  空:true; 非空:false
     */
    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }

方式二

//蛇形转驼峰
public String snake_case2camalCase(String selected){
    selected = selected.replaceAll("_([A-Z])", "$1");
    int i = -32;

    for(char c = 'a'; c <= 'z'; ++c) {
        selected = selected.replaceAll("_" + c, String.valueOf((char)(c + i)));
    }
    return selected;

}

//驼峰转蛇形
public String camalCase2snake_case(String selected){
    selected = selected.replaceAll("[A-Z]", "_$0");
                selected = selected.toLowerCase();
                if (selected.charAt(0) == '_') {
                    selected = selected.substring(1);
                }
    return selected;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值