字串處理工具類

entaro發表於2022-01-17

1、駝峰轉下劃線操作

    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

2、下劃線轉駝峰

public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        boolean flag = false; // "_" 後轉大寫標誌,預設字元前面沒有"_"
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                flag = true;
                //標誌設定為true,跳過
            } else {
                if (flag) {
                    //表示當前字元前面是"_" ,當前字元轉大寫
                    sb.append(Character.toUpperCase(param.charAt(i)));
                    flag = false;  //重置標識
                } else {
                    sb.append(Character.toLowerCase(param.charAt(i)));
                }
            }
        }
        return sb.toString();
    }
``````java
public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        boolean flag = false; // "_" 後轉大寫標誌,預設字元前面沒有"_"
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                flag = true;
                //標誌設定為true,跳過
            } else {
                if (flag) {
                    //表示當前字元前面是"_" ,當前字元轉大寫
                    sb.append(Character.toUpperCase(param.charAt(i)));
                    flag = false;  //重置標識
                } else {
                    sb.append(Character.toLowerCase(param.charAt(i)));
                }
            }
        }
        return sb.toString();
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章