如题,工具方法,项目中用到的字符命名方式需要互转,不依赖任何第三方库,不挑JDK版本,复制粘贴即可用
下划线命名方式:some_name
驼峰命名方式:someName
public static void main(String[] args) throws Exception { System.out.println(underscoreToCamel("some_key")); System.out.println(camelToUnderline("someKey")); } /** * 下划线命名转驼峰方式,例如some_key转成someKey */ public static String underscoreToCamel(String underscore) { if (underscore == null) { return null; } String[] split = underscore.split("_"); StringBuilder sb = new StringBuilder(underscore.length()); for (String s : split) { char[] chars = s.toCharArray(); if (chars[0] < 'A' || chars[0] > 'Z') { if (chars[0] >= 'a' && chars[0] <= 'z') { chars[0] -= 32; } } sb.append(chars); } return sb.toString(); } /** * 驼峰转下划线命名方式,例如someKey转成some_key */ public static String camelToUnderline(String camel) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < camel.length(); ++i) { char ch = camel.charAt(i); if (ch >= 'A' && ch <= 'Z') { char c = (char) (ch + 32); if (i > 0) { buf.append('_'); } buf.append(c); } else { buf.append(ch); } } return buf.toString(); }
另一种更简单的驼峰转SnakeCase的方式:
public static String camelToSnakeCase(String str) { return str.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase(); }
文章评论