【问题标题】:converting string of unicode "\u0063" into "c"将unicode字符串“\u0063”转换为“c”
【发布时间】:2014-10-17 01:20:14
【问题描述】:

我正在做一些密码分析作业,并试图编写执行 a + b = c 的代码。我的想法是使用 unicode。 b +(b-a) = c。问题是我的代码返回 c 的 unicode 值而不是字符串“c”,我无法转换它。

请有人解释一下下面称为 unicode 的字符串与称为 test 和 test2 的字符串之间的区别吗?还有什么方法可以让字符串 unicodeOfC 打印“c”?

//this calculates the unicode value for c
String unicodeOfC = ("\\u" + Integer.toHexString('b'+('b'-'a') | 0x10000).substring(1));

//this prints \u0063
System.out.println(unicodeOfC);

String test = "\u0063";

//this prints c
System.out.println(test);

//this is false
System.out.println(test.equals(unicodeOfC));

String test2 = "\u0063";
//this is true
System.out.println(test.equals(test2));

【问题讨论】:

    标签: java string unicode


    【解决方案1】:

    testtest2 之间没有区别。它们都是Stringliterals,指的是同一个String。这个String 文字由unicode escape 组成。

    首先是 Java 编程语言的编译器(“Java 编译器”) 识别其输入中的 Unicode 转义,翻译 ASCII 字符 \u 后跟 UTF-16 代码的四个十六进制数字 指定十六进制值的单位(§3.1),并传递所有其他 字符不变。

    所以编译器会翻译这个 unicode 转义,并将其转换为相应的 UTF-16 代码单元。也就是说,unicode 转义 \u0063 转换为字符 c

    在这

    String unicodeOfC = ("\\u" + Integer.toHexString('b'+('b'-'a') | 0x10000).substring(1));
    

    String 文字 "\\u"(使用 \ 字符转义 \ 字符)的运行时值为 \u,即。 \u 这两个字符。 String 与调用 toHexString(..) 的结果相连。然后,您在生成的String 上调用substring,并将其结果分配给unicodeOfC。所以String 的值为\u0063,即。 6 个字符 \u0063

    还有什么方法可以让字符串unicodeOfC 打印“c”?

    与您创建它的方式类似,您需要获取 unicode 转义的数字部分,

    String numerical = unicodeOfC.replace("\\u", "");
    int val = Integer.parseInt(numerical, 16);
    System.out.println((char) val);
    

    然后您可以将其打印出来。

    【讨论】:

    • 太好了,我理解您的回答,并感谢附加代码按我的要求工作。非常感谢您的帮助。
    【解决方案2】:

    我认为您不了解字符串转义的工作原理。

    在 Java 中,反斜杠是一个转义字符,允许您在字符串中使用字符,例如换行符 \n、制表符 \t 或 unicode \u0063

    假设我正在编写代码并且我需要打印一个换行符。我会这样做System.out.println("\n");

    现在假设我想显示一个反斜杠,System.out.println("\"); 将是一个编译错误,但System.out.println("\\"); 将打印\

    所以你的第一个字符串是打印文字反斜杠字符,然后是字母 u,然后是十六进制数字。

    【讨论】:

    • 谢谢!我知道 \n 等,所以当你这样说时它是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2013-08-21
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多