String(1) : 驼峰与下划线拼接格式转换
程序员文章站
2022-03-09 09:28:24
...
public static void main(String[] args) {
String str = "xin_yang_sheng_guang_ba";
System.err.println(str);
System.err.println(xiaHuaXianToTuoFeng(str));
System.err.println(tuoFengToxiaHuaXian(xiaHuaXianToTuoFeng(str)));
}
/**
* 驼峰转下划线
*
* @param str
* @return
*/
public static String tuoFengToxiaHuaXian(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
sb.append("_").append(Character.toLowerCase(str.charAt(i)));
} else {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
/**
* 下划线转驼峰
*
* @param str
* @return
*/
public static String xiaHuaXianToTuoFeng(String str) {
String[] strings = str.split("_");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
if (i == 0) {
sb.append(strings[i]);
} else {
sb.append(strings[i].substring(0, 1).toUpperCase() + strings[i].substring(1));
}
}
return sb.toString();
}
END。