英文:
In Java, length of "\1", "\12", "\377", "\378, what are the differences and why?
问题
答案是1, 1, 1, 2。
为什么"\377"的长度是1?为什么"\378"的长度是2?有什么区别?
能有人帮忙解释一下吗?谢谢。
英文:
The answers are 1, 1, 1, 2.
Why the length of "\377" is 1? And why the length of "\378" is 2? What is the difference?
Could someone help out? Thanks.
答案1
得分: 1
那些是八进制转义。它们是表示 Unicode 字符的方式,但仅限于 U+0000 到 U+00FF 的范围。
它们基本上只是为了与 C 兼容而存在。我觉得这个原因有点薄弱,因为大多数 Java 与 C 不兼容,但我猜这意味着你至少可以将更多的字符串字面量从 C 代码复制到 Java 代码中。
\377
是最高的八进制转义,表示 U+00FF。因此 "\378"
被解释为八进制转义 \37
后面跟着普通的字符 8
。
在 Java 中,更常见且更有用的转义(任意)Unicode 字符的方式是Unicode 转义。它们看起来像是 \u0020
(即 \u
后面跟着确切的 4 个十六进制数字)。
英文:
Those are octal escapes. They are ways to represent Unicode characters, but only in the range of U+0000 to U+00FF.
They exist basically only for compatibility with C. I find that reason a bit weak, since most of Java is not compatible to C anyway, but I guess this means you can at least copy more of the string literals from C code to Java code.
\377
is the highest possible octal escape, representing U+00FF. Thus "\378"
is interpreted as the octal escape \37
followed by the plain old character 8
.
In Java the more common and more useful way to escape (arbitrary) Unicode characters are Unicode Escapes. They look like \u0020
(i.e. \u
followed by exactly 4 hex digits).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论