【发布时间】:2021-03-24 20:09:12
【问题描述】:
如何将包含代理对字符和普通字符的 unicode 字符串拆分为 List<String> 个字符?
(需要String 来存储由两个char 组成的代理对字符)
【问题讨论】:
如何将包含代理对字符和普通字符的 unicode 字符串拆分为 List<String> 个字符?
(需要String 来存储由两个char 组成的代理对字符)
【问题讨论】:
试试这个。
String s = "?a?c?";
List<String> result = List.of(s.split("(?<=.)"));
for (String e : result)
System.out.println(e + " : length=" + e.length());
输出:
? : length=2
a : length=1
? : length=2
c : length=1
? : length=2
或者,使用code point 整数流。
List<String> result =
s
.codePoints() // Produce a `IntStream` of code point numbers.
.mapToObj(Character::toString) // Produce a `String` containing one or two java chars for each code point in the stream.
.collect(Collectors.toList());
看到这个code run live at IdeOne.com。
要捕获代码点,请使用上述代码的这种变体。
List<Integer> codePointNumbers =
s
.codePoints()
.boxed()
.collect( Collectors.toList() ) ;
运行时:
codePointNumbers.toString(): [128522, 97, 128102, 99, 128522]
【讨论】:
List<Integer> 存储代码点会更容易。
char 类型已过时,无法表示大多数 Unicode 字符。杂耍char 值来表示现代Unicode 文本是令人沮丧和不必要的。寻找添加到String 和Character 类的几个面向代码点的方法。我在此答案中添加了另一个代码示例,展示了如何收集代码点整数。