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 the IndexOutOfBoundsException 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 the index has fewer code points than codePointOffset.
  • The codePointOffset is negative and the subsequence of the string before the index has fewer code points than the absolute value of codePointOffset.

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.

Free Resources