How to get the substring that contains the first N

2019-02-17 14:29发布

问题:

The String datatype in Java lets us know how many unicode chars exit in a string by codePointCount; and how to get the n-th unicode char by codePointAt. I was wonding if there is an API to get the substring that contains the first N unicode characters in Java.

Thanks,

回答1:

There's not a method that does it in one call, but offsetByCodePoints() will help you do this.

static String substring(String str, int idx, int len) {
  return str.substring(idx, str.offsetByCodePoints(idx, len));
}