驼峰命名法工具优化,使用下划线开头的时候忽略它

This commit is contained in:
thinkgem
2025-09-18 21:47:28 +08:00
parent 23ea3e5020
commit cb4640cbb7
2 changed files with 40 additions and 10 deletions

View File

@@ -270,7 +270,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
}
/**
* 驼峰命名法工具
* 转换为驼峰命名法
* @return
* camelCase("hello_world") == "helloWorld"
* capCamelCase("hello_world") == "HelloWorld"
@@ -283,37 +283,35 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
for (int i = 0, j = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == UNDERLINE.charAt(0) || c == MINUS.charAt(0)) {
upperCase = i != 1; // 不允许第二个字符是大写
upperCase = j > 1; // 不允许第二个字符是大写
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
j++;
} else {
sb.append(c);
j++;
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
* 转换为驼峰命名法(首字母大写)
* @return
* camelCase("hello_world") == "helloWorld"
* capCamelCase("hello_world") == "HelloWorld"
* uncamelCase("helloWorld") = "hello_world"
*/
public static String capCamelCase(String s) {
if (s == null) {
return null;
}
s = camelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
return cap(camelCase(s));
}
/**
* 驼峰命名法工具
* 取消驼峰命名
* @return
* camelCase("hello_world") == "helloWorld"
* capCamelCase("hello_world") == "HelloWorld"

View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
*/
package com.jeesite.test.lang;
import com.jeesite.common.lang.StringUtils;
import java.text.ParseException;
/**
* 字符串工具测试类
* @author ThinkGem
* @version 2025-09-18
*/
public class StringUtilsTest {
public static void main(String[] args) throws ParseException {
System.out.println(StringUtils.camelCase("id_name") + " = idName");
System.out.println(StringUtils.camelCase("_id_name") + " = idName");
System.out.println(StringUtils.camelCase("__id_name") + " = idName");
System.out.println(StringUtils.camelCase("a_id") + " = aid");
System.out.println(StringUtils.camelCase("a_b_id") + " = abId");
System.out.println(StringUtils.camelCase("__a_id") + " = aid");
System.out.println(StringUtils.camelCase("__a_b_id") + " = abId");
System.out.println(StringUtils.capCamelCase("id_name") + " = IdName");
System.out.println(StringUtils.capCamelCase("a_b_id_name") + " = AbIdName");
System.out.println(StringUtils.uncamelCase("abIdName") + " = ab_id_name");
System.out.println(StringUtils.uncamelCase("AbIdName") + " = ab_id_name");
}
}