如何将“\u”与控制台输出的UTF-8代码结合? (Java)

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

How can I combine *\u" and the UTF-8 code for console output? (Java)

问题

我想将"\u"与包含Hex代码的String组合起来,以便我可以在控制台中打印出Unicode字符。

我尝试过类似这样的方法,但控制台只打印普通文本,例如\uf600

ArrayList<String> arr = new ArrayList<String>();
emoji.codePoints()
        .mapToObj(Integer::toHexString)
        .forEach((n) -> arr.add(n));  // arr will contain hex strings

for (int i = 1; i < arr.size(); i += 2) {
    System.out.println("\\u" + arr.get(i));
}
英文:

I would like to combine a &quot;\u&quot; with a String that contains a Hex-Code so that I can print out a unicode character in the console.

I've tried something like this, but the console only prints regular text, eg \uf600:

ArrayList&lt;String&gt; arr = new ArrayList&lt;String&gt;();
emoji.codePoints()
    .mapToObj(Integer::toHexString)
    .forEach((n) -&gt; arr.add(n));  // arr will contain hex strings

for (int i = 1; i &lt; arr.size(); i += 2) {
	 System.out.println(&quot;\\u&quot; + arr.get(i));
}

答案1

得分: 2

在Java中,\u 仅存在于编译器中,作为一种便利方式,帮助你在源代码中添加Unicode字符字面量。如果在运行时创建一个包含 \u 后跟十六进制数字的字符串,没有机制可以将其转换为单个 char

听起来你想将每个代码点分别转换为一个字符串。以下是一种可以实现的方法:使用 Character.toChars 将代码点转换为字符数组,然后从字符数组构建一个新的字符串:

ArrayList<String> arr = new ArrayList<String>();
emoji.codePoints().mapToObj(Character::toChars).map(String::new)
    .forEach(arr::add)
英文:

In Java, \u exists only in the compiler, as a convenience to help you add unicode character literals in your source code. If at run time you create a string that contains \ u followed by hex digits, there is no mechanism in place to transform it into a single char.

It sounds like you want to transform each code point separately to a string. Here is one way you can do that: use Character.toChars to transform the code point to a char array, and then build a new string from the char array:

ArrayList&lt;String&gt; arr = new ArrayList&lt;String&gt;();
emoji.codePoints().mapToObj(Character::toChars).map(String::new)
    .forEach(arr::add)

huangapple
  • 本文由 发表于 2020年8月6日 20:53:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63284052.html
匿名

发表评论

匿名网友

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

确定