What is the String offsetByCodePoints() method in Java?
The offsetByCodePoints() method in Java is used to return the index within a string that is the offset from the given index by codePointOffset code points.
Syntax
The offsetByCodePoints() method can be declared as shown in the code below:
public int offsetByCodePoints(int index, int codePointOffset)
index: The index that is to be offset.codePointOffset: The offset in code points.
Return value
The offsetByCodePoints() method returns the index within this string that is the offset from the given index by codePointOffset code points.
Note: The
offsetByCodePoints()method throws theIndexOutOfBoundsExceptionif it satisfies any of the following conditions:
- The
indexis negative.- The
indexis greater than the length of the string.- The
codePointOffsetis positive and the subsequence of the string starting from theindexhas fewer code points thancodePointOffset.- The
codePointOffsetis negative and the subsequence of the string before theindexhas fewer code points than the absolute value ofcodePointOffset.
Example
Consider the code below, which demonstrates the use of the offsetByCodePoints() method:
import java.lang.*;public class Main {public static void main(String[] args) {String str = "offsetByCodePoints() example";System.out.println("str: " + str);int ind = str.offsetByCodePoints(2, 6);System.out.println("index = " + ind);}}
Explanation
A string str is declared in line 7. The offsetByCodePoints() method is used in line 10 to get the index within str that is the offset from the given index 2 by 6 code points.