Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 840
Joe C Avatar asked Jan 28 '14 04:01

Joe C


People also ask

How do you get the first n characters of a string?

Use the String. slice() method to get the first N characters of a string, e.g. str.

How do you extract the first 5 characters from the string str Java?

To access the first n characters of a string in Java, we can use the built-in substring() method by passing 0, n as an arguments to it. 0 is the first character index (that is start position), n is the number of characters we need to get from a string.

Does substring include the first character?

The substring begins with the character at the specified index and extends to the end of this string.


1 Answers

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));
}
like image 197
erickson Avatar answered Oct 24 '22 06:10

erickson