作为参数传递时,在 Java 中正确表示 ^A (Unicode \u0001)

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

Representing ^A (Unicode \u0001) correctly in Java when passed as argument

javaunicodespecial-characters

提问by vinayak_narune

 public class TestU {
    public static void main(String[] args) {
        String str = "\u0001";
        System.out.println("str-->"+str);
        System.out.println("arg[0]-->"+args[0]);
    }
}

Output :

输出 :

str-->^A
arg[0]-->\u0001

I am passing arg[0]as \u0001

我传递arg[0]\u0001

I executed this code in linux, the command line variable is not taken as unicode special character.

我在linux中执行了这段代码,命令行变量没有被当作unicode特殊字符。

回答by CoderCroc

The argument you pass from command line is not actually unicode character but it's a Stringof unicode character which is escaped with \. Ultimately, your String will become \\u0001and that's why it is printing \u0001. Same way, if you enter \as a command line argument it will become \\to escape your backward slash.

您从命令行传递的参数实际上不是 unicode 字符,而是Stringunicode 字符,用\. 最终,您的 String 将变成\\u0001,这就是它正在打印的原因\u0001。同样,如果您\作为命令行参数输入,它将\\转义您的反斜杠。

While the Stringyou have declared in main is actually unicode character.

虽然String您在 main 中声明的实际上是 unicode 字符。

String escapedstring = "\u0001";//in args[0]
String unicodeChar = "\u0001";// in str

So, now you want \\u0001to be converted into \u0001and there are lot of ways to achieve that. i.e.you can use StringEscapeUtils#unescapeJavamethod of utility or you can also try following way.

所以,现在你想\\u0001被转换成,\u0001并且有很多方法可以实现。您可以使用StringEscapeUtils#unescapeJava实用程序的方法,也可以尝试以下方式。

String str = "\u0001";
char unicodeChar = (char) Integer.parseInt(str.substring(2));
System.out.println(unicodeChar);

NOTE: You can find other ways to convert unicode String to unicode characters in following question.(Already provided in comment by Marcinek)

注意:您可以在以下问题中找到将 unicode String 转换为 unicode 字符的其他方法。(已在评论中提供Marcinek