public class CamelCaseUtils{
private static final char SEPARATOR ='_';
/**
* 驼峰转下划线
* @param s
* @return
*/
public static StringtoUnderlineName(String s) {
if (s ==null) {
return null;
}
StringBuilder sb =new StringBuilder();
boolean upperCase =false;
for (int i =0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase =true;
if (i <(s.length() -1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i +1))||Character.isDigit(s.charAt(i +1));
}
if ((i >=0) && Character.isUpperCase(c)) {
boolean flag =!upperCase || !nextUpperCase;
if (flag) {
if (i >0) sb.append(SEPARATOR);
}
upperCase =true;
} else {
upperCase =false;
}
sb.append(Character.toUpperCase(c));
}
return sb.toString();
}
/**
* 下划线转小驼峰
* @param s
* @return
*/
public static StringtoCamelCase(String s) {
if (s ==null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb =new StringBuilder(s.length());
boolean upperCase =false;
for (int i =0; i < s.length(); i++) {
char c = s.charAt(i);
if (c ==SEPARATOR) {
upperCase =true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase =false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 下划线转大驼峰
* @param s
* @return
*/
public static StringtoCapitalizeCamelCase(String s) {
if (s ==null) {
return null;
}
s =toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
public static void main(String[] args) {
System.out.println(CamelCaseUtils.toUnderlineName("ABCD1111"));
System.out.println(CamelCaseUtils.toUnderlineName("AaBCD1111"));
System.out.println(CamelCaseUtils.toUnderlineName("AaBCDaaA1111"));
System.out.println(CamelCaseUtils.toCamelCase("A_aaB_C_DaaA1111"));
System.out.println(CamelCaseUtils.toCapitalizeCamelCase("A_aaB_C_DaaA1111"));
}
}
网友评论