在Java中,”\1″、”\12″、”\377″、”\378″ 的长度有什么区别,以及为什么?

huangapple go评论65阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2020年9月17日 15:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63933549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定