Java中的特殊字符\ 0 {NUL}

如何在String中替换\ 0(NUL)?

String b = "2012yyyy06mm"; // sth what i want String c = "2\0\0\0012yyyy06mm"; String d = c.replaceAll("\\\\0", ""); // not work String e = d.replace("\0", ""); // er, the same System.out.println(c+"\n"+d+"\n"+e); String bb = "2012yyyy06mm"; System.out.println(b.length() + " > " +bb.length()); 

上面的代码将在控制台中打印12> 11。 哎呀,发生什么事了?

 String e = c.replace("\0", ""); System.out.println(e); // just print 2(a bad character)2yyyy06mm 

你的字符串"2\0\0\0012yyyy06mm"没有开始2 {NUL} {NUL} {NUL} 0 1 2 ,而是包含2 {NUL} {NUL} {SOH} 2

\001被视为单个ASCII 1字符( SOH ),而不是NUL后跟1 2

结果是只删除了两个字符,而不是三个。

我认为除了将字符串分开之外,还没有任何方法可以表示缩写八进制转义后的数字:

 String c = "2" + "\0\0\0" + "012yyyy06mm"; 

或者,在(最后一个)八进制转义中指定所有三个数字,以便后面的数字不被解释为八进制转义的一部分:

 String c = "2\000\000\000012yyyy06mm"; 

完成后,根据您的行替换"\0"

 String e = c.replace("\0", ""); 

会正常工作。