java中驼峰命名和下划线命名互转方法(代码实现)

黑泽君
发布
于
2018-10-12 10:29:58
发布
于
2018-10-12 10:29:58
1 /**
2 * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
3 * 例如:HelloWorld->HELLO_WORLD
4 * @param name 转换前的驼峰式命名的字符串
5 * @return 转换后下划线大写方式命名的字符串
6 */
7 public static String underscoreName(String name) {
8 StringBuilder result = new StringBuilder();
9 if (name != null && name.length() > 0) {
10 // 将第一个字符处理成大写
11 result.append(name.substring(0, 1).toUpperCase());
12 // 循环处理其余字符
13 for (int i = 1; i < name.length(); i++) {
14 String s = name.substring(i, i + 1);
15 // 在大写字母前添加下划线
16 if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
17 result.append("_");
18 }
19 // 其他字符直接转成大写
20 result.append(s.toUpperCase());
21 }
22 }
23 return result.toString();
24 }
1 /**
2 * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
3 * 例如:HELLO_WORLD->HelloWorld
4 * @param name 转换前的下划线大写方式命名的字符串
5 * @return 转换后的驼峰式命名的字符串
6 */
7 public static String camelName(String name) {
8 StringBuilder result = new StringBuilder();
9 // 快速检查
10 if (name == null || name.isEmpty()) {
11 // 没必要转换
12 return "";
13 } else if (!name.contains("_")) {
14 // 不含下划线,仅将首字母小写
15 return name.substring(0, 1).toLowerCase() + name.substring(1);
16 }
17 // 用下划线将原始字符串分割
18 String camels[] = name.split("_");
19 for (String camel : camels) {
20 // 跳过原始字符串中开头、结尾的下换线或双重下划线
21 if (camel.isEmpty()) {
22 continue;
23 }
24 // 处理真正的驼峰片段
25 if (result.length() == 0) {
26 // 第一个驼峰片段,全部字母都小写
27 result.append(camel.toLowerCase());
28 } else {
29 // 其他的驼峰片段,首字母大写