Java中的特殊字符\0 {NUL} [英] Special characters \0 {NUL} in Java

查看:874
本文介绍了Java中的特殊字符\0 {NUL}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在字符串中替换\0(NUL)?

How to replace \0 (NUL) in the String?

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。哎呀,发生什么事了?

The above code will print 12 > 11 in console. Oops, What happened?

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


推荐答案

你的字符串2 \\\\0012yyyy06mm无法启动 2 {NUL} {NUL} {NUL} 0 1 2 ,而是包含 2 {NUL} {NUL} {SOH} 2

Your string "2\0\0\0012yyyy06mm" does not start 2 {NUL} {NUL} {NUL} 0 1 2, but instead contains 2 {NUL} {NUL} {SOH} 2.

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

The \001 is treated as a single ASCII 1 character (SOH) and not as a NUL followed by 1 2.

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

The result is that only two characters are being removed, not three.

我认为没有办法在缩写八进制转义,而不是将字符串分开:

I don't think there's any way to represent digits following an abbreviated octal escape other than by breaking the string apart:

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

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

or alternately, specify all three digits in the (last) octal escape such that the following digits are not interpreted as being part of the octal escape:

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

完成后,替换\0根据你的行:

Once you've done that, replacing "\0" as per your line:

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

将正常工作。

这篇关于Java中的特殊字符\0 {NUL}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆