\x 在 Java 中转义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3613759/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:40:42  来源:igfitidea点击:

\x Escape in Java?

javahexescaping

提问by David

I was wondering if there is a similar hex (\x) escape in Java like there is in C++. For example:

我想知道 Java 中是否有类似 C++ 中的十六进制 (\x) 转义。例如:

char helloworld[] = "\x48\x45\x4C\x4C\x4F\x20\x57\x47\x52\x4C\x44";
printf("%s", helloworld);

There is no hex (\x) escape in Java from what it appears so far. Is there an alternative that is just as easy to use without having to concat a bunch of hex numbers together?

到目前为止,Java 中没有十六进制 (\x) 转义。有没有一种替代方法既易于使用又无需将一堆十六进制数字连接在一起?

采纳答案by erickson

Strings in Java are always encoded in UTF-16, so it uses a Unicode escape: \u0048. Octal characters are supported as well: \110

Java 中的字符串总是以 UTF-16 编码,因此它使用 Unicode 转义:\u0048. 也支持八进制字符:\110

回答by tschodt

Note that Unicode escapes are parsed quite early. It can come as a surprise when

请注意,Unicode 转义很早就被解析了。当

  String s = "text\u000d\u000a";

causes a compiler error because you should have used "text\015\012"or "text\r\n"

导致编译器错误,因为您应该使用"text\015\012""text\r\n"