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,
Use the String. slice() method to get the first N characters of a string, e.g. str.
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.
The substring begins with the character at the specified index and extends to the end of this string.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With