英文:
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 "\u"
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<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));
}
答案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<String> arr = new ArrayList<String>();
emoji.codePoints().mapToObj(Character::toChars).map(String::new)
.forEach(arr::add)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论