java中駝峰與下橫線格式字串互轉演算法
阿新 • • 發佈:2018-12-19
public static final char UNDERLINE = '_'; /** * 駝峰格式字串轉換為下劃線格式字串 * * @param param * @return */ 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)); } else { sb.append(c); } } return sb.toString(); } /** * 下劃線格式字串轉換為駝峰格式字串 * * @param param * @return */ public static String underlineToCamel(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 (c == UNDERLINE) { if (++i < len) { sb.append(Character.toUpperCase(param.charAt(i))); } } else { sb.append(c); } } return sb.toString(); } /** * 下劃線格式字串轉換為駝峰格式字串2 * * @param param * @return */ public static String underlineToCamel2(String param) { if (param == null || "".equals(param.trim())) { return ""; } StringBuilder sb = new StringBuilder(param); Matcher mc = Pattern.compile("_").matcher(param); int i = 0; while (mc.find()) { int position = mc.end() - (i++); sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase()); } return sb.toString(); } public static void main(String[] args) { String aaa = "app_version_fld"; System.out.println(underlineToCamel(aaa)); System.out.println(underlineToCamel2(aaa)); aaa = "appVersionFld"; System.out.println(camelToUnderline(aaa)); }