Java 中字符零 (0) 的含义是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9753576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the meaning of char zero (0) in Java?
提问by Carlos Gavidia-Calderon
Possible Duplicate:
Java string replace and the NUL (NULL, ASCII 0) character?
I'm doing some String algorithms in Java, and i noticed that wherever i include a char with the value of 0 (zero) it marks the end of the String. Like this:
我正在用 Java 做一些字符串算法,我注意到无论我在哪里包含一个值为 0(零)的字符,它都标志着字符串的结束。像这样:
String aString = "I'm a String";
char[] aStringArray = aString.toCharArray();
aStringArray[1] = 0;
System.out.println(new String(aStringArray)); //It outputs "I"
What's the reason/cause of this behaviour?
这种行为的原因/原因是什么?
采纳答案by óscar López
The character '\0'
is the null character. It's a control character, and it does notterminate the string, that's not how strings work in Java (that's how they work in C, though.)
该字符'\0'
为空字符。它是一个控制字符,它不会终止字符串,这不是字符串在 Java 中的工作方式(不过,这就是它们在 C 中的工作方式。)
回答by Java42
For some additional insight, add the following to you code:
要获得更多见解,请将以下内容添加到您的代码中:
System.out.println(new String(aStringArray).length());
for (Byte b : new String(aStringArray).getBytes()) {
System.out.print("["+b+"]");
}
Your rendering system (console or output window) is not displaying everything.
您的渲染系统(控制台或输出窗口)并未显示所有内容。
回答by M Platvoet
I'm wondering if you have posted your actual code. When using the String(byte[])constructor the actual length of the string is dependent on the contents of the array.
我想知道你是否已经发布了你的实际代码。使用String(byte[])构造函数时,字符串的实际长度取决于数组的内容。