【发布时间】:2014-02-19 05:48:19
【问题描述】:
Java 中的 String 数据类型通过 codePointCount 让我们知道字符串中有多少个 unicode 字符;以及如何通过 codePointAt 获取第 n 个 unicode char。我想知道是否有 API 可以获取包含 Java 中前 N 个 unicode 字符的子字符串。
谢谢,
【问题讨论】:
Java 中的 String 数据类型通过 codePointCount 让我们知道字符串中有多少个 unicode 字符;以及如何通过 codePointAt 获取第 n 个 unicode char。我想知道是否有 API 可以获取包含 Java 中前 N 个 unicode 字符的子字符串。
谢谢,
【问题讨论】:
查看java源代码:java.util.stream.Collectors#joining()
.codePoints().limit(255) // limit as you need
.collect(StringBuilder::new, StringBuilder::appendCodePoint, null)
【讨论】:
没有一种方法可以一次性完成,但offsetByCodePoints() 会帮助您做到这一点。
static String substring(String str, int idx, int len) {
return str.substring(idx, str.offsetByCodePoints(idx, len));
}
【讨论】:
substring(str.offsetByCodePoints(0, idx), str.offsetByCodePoints(0, idx+len))吗?
idx参数是字符偏移量还是码点偏移量。字符串方法一般采用字符偏移量,而那些使用码点的方法旨在将码点偏移量转换为字符偏移量。