简体   繁体   中英

How to get the substring that contains the first N unicode characters in Java

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,

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));
}

See java source at: java.util.stream.Collectors#joining()

.codePoints().limit(255) // limit as you need
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM