17-字符串工具类
字符串转驼峰
java
public class CamelCaseConverterUtil {
// 将字符串转换为小驼峰格式 (lowerCamelCase)
public static String toLowerCamelCase(String str) {
StringBuilder result = new StringBuilder();
String[] parts = str.split("_");
for (int i = 0; i < parts.length; i++) {
if (i == 0) {
// 第一个单词首字母小写
result.append(parts[i].toLowerCase());
} else {
// 其他单词首字母大写
result.append(parts[i].substring(0, 1).toUpperCase());
result.append(parts[i].substring(1).toLowerCase());
}
}
return result.toString();
}
// 将字符串转换为大驼峰格式 (UpperCamelCase)
public static String toUpperCamelCase(String str) {
StringBuilder result = new StringBuilder();
String[] parts = str.split("_");
for (String part : parts) {
// 每个单词首字母大写
result.append(part.substring(0, 1).toUpperCase());
result.append(part.substring(1).toLowerCase());
}
return result.toString();
}
public static void main(String[] args) {
String input = "hello_world_example";
String lowerCamelCase = toLowerCamelCase(input);
String upperCamelCase = toUpperCamelCase(input);
System.out.println("输入字符串: " + input);
System.out.println("小驼峰 (lowerCamelCase): " + lowerCamelCase);
System.out.println("大驼峰 (UpperCamelCase): " + upperCamelCase);
}
}