如何获取包含Java中前N个unicode字符的子字符串

Joe*_*e C 5 java unicode substring

Java中的String数据类型让我们知道codePointCount在字符串中退出了多少个unicode字符; 以及如何通过codePointAt获取第n个unicode char.我想知道是否有一个API来获取包含Java中前N个unicode字符的子字符串.

谢谢,

eri*_*son 9

没有一种方法可以在一次调用中完成,但offsetByCodePoints()会帮助您完成此操作.

static String substring(String str, int idx, int len) {
  return str.substring(idx, str.offsetByCodePoints(idx, len));
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是必须是`substring(str.offsetByCodePoints(0,idx),str.offsetByCodePoints(0,idx + len))`? (3认同)