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.
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.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 theIndexOutOfBoundsException
if it satisfies any of the following conditions:
- The
index
is negative.- The
index
is greater than the length of the string.- The
codePointOffset
is positive and the subsequence of the string starting from theindex
has fewer code points thancodePointOffset
.- The
codePointOffset
is negative and the subsequence of the string before theindex
has fewer code points than the absolute value ofcodePointOffset
.
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);}}
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.