@Test
public void testCamelCase() {
String orig="want_to_be_a_camel";
String camel=orig.replaceAll("_([a-z])", "$1".toUpperCase());
System.out.println(camel);
assertEquals("wantToBeACamel", camel);
}
显示“wanttobeacamel”后失败。为什么没有大写字符?
java version "1.6.0_29"
Java(TM) SE Runtime Environment (build 1.6.0_29-b11)
Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02, mixed mode)
========= 验尸:
使用简单的 replaceAll 是一条死胡同。我这样做只是为了教我的孩子编码......但是对于提出要求的 Jayamohan,这是另一种方法。
public String toCamelCase(String str) {
if (str==null || str.length()==0) {
return str;
}
char[] ar=str.toCharArray();
int backref=0;
ar[0]=Character.toLowerCase(ar[0]);
for (int i=0; i<ar.length; i++) {
if (ar[i]=='_') {
ar[i-backref++]=Character.toUpperCase(ar[i+++1]);
} else {
ar[i-backref]=ar[i];
}
}
return new String(ar).substring(0,ar.length-backref);
}