public class TestU {
public static void main(String[] args) {
String str = "\u0001";
System.out.println("str-->"+str);
System.out.println("arg[0]-->"+args[0]);
}
}
输出:
str-->^A
arg[0]-->\u0001
我将 arg[0]
作为 \u0001
我在linux中执行了这段代码,命令行变量不被视为unicode特殊字符。
最佳答案
您从命令行传递的参数实际上不是 unicode 字符,而是用 \
转义的 unicode 字符的 String
。最终,您的字符串将变为 \\u0001
,这就是它打印 \u0001
的原因。同样,如果您输入 \
作为命令行参数,它将变成 \\
以转义反斜杠。
虽然你在main中声明的String
实际上是unicode字符。
String escapedstring = "\\u0001";//in args[0]
String unicodeChar = "\u0001";// in str
所以,现在您希望将 \\u0001
转换为 \u0001
,并且有很多方法可以实现这一目标。 即您可以使用 StringEscapeUtils#unescapeJava
实用程序方法,也可以尝试以下方法。
String str = "\\u0001";
char unicodeChar = (char) Integer.parseInt(str.substring(2));
System.out.println(unicodeChar);
注意:您可以在以下问题中找到将 unicode 字符串转换为 unicode 字符的其他方法。(已在 Marcinek
的评论中提供)
关于java - 当作为参数传递时,在 Java 中正确表示 ^A (Unicode\u0001),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470445/