Java下划线驼峰转换

ⅰ亾dé卋堺 提交于 2020-01-26 02:49:54
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();
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!