Java下划线驼峰转换

public class CamelConvert {
    public static final char UNDERLINE = '_';

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    public static void main(String[] args) {
        System.out.println(underlineToCamel("mer_id"));
        System.out.println(underlineToCamel("mer_name"));
        System.out.println(underlineToCamel("usr_mp_cover"));
        System.out.println(underlineToCamel("usr_mp_cipher"));
        System.out.println(underlineToCamel("mer_email_cover"));
        System.out.println(underlineToCamel("mer_email_cipher"));
        System.out.println(underlineToCamel("social_credit_code"));
        System.out.println(underlineToCamel("instu_code"));
        System.out.println(underlineToCamel("oper_date"));
        System.out.println(underlineToCamel("oper_time"));
        System.out.println(humpToLine2("merId"));
    }

    /**
     * 下划线格式字符串转换为驼峰格式字符串
     *
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        param = param.toLowerCase();
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (i == 0) {//首字母大写
                char c1 = param.charAt(0);
                sb.append(Character.toUpperCase(c1)); //此处控制首字母大小写
                continue;
            }
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public static String humpToLine2(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString());
        return sb.toString();
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值