Lehman-Blog - 驼峰
type: channel
link: https://blog.lehman.top/tag/%E9%A9%BC%E5%B3%B0/
items: 驼峰下划线互转

驼峰下划线互转
type: item
date: 2020-08-12T14:41:00+08:00
description: [scode type="blue"] js实现[/scode] // 字符串下划线转驼峰 const formatToHump = (value) => { return value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase()) } // 字符串驼峰转下划线 const formatToLine = (value) => { return value.replace(/([A-Z])/g, '_$1').toLowerCase() } [scode type="blue"]Java实现[/scode] private static final char UNDERLINE='_'; /** * 下划线 转 驼峰 * @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 = Character.toLowerCase(param.charAt(i)); if (c == UNDERLINE){ if (++i<len){ sb.append(Character.toUpperCase(param.charAt(i))); } }else{ sb.append(c); } } return sb.toString(); } /** * 驼峰命名转为下划线命名 * @param para * @return */ public static String HumpToUnderline(String para){ StringBuilder sb=new StringBuilder(para); int temp=0;//定位 if (!para.contains("_")) { for(int i=0;i<para.length();i++){ if(Character.isUpperCase(para.charAt(i))){ sb.insert(i+temp, "_"); temp+=1; } } } return sb.toString().toUpperCase(); }