The offsetByCodePoints(int index, int codePointOffset) method returns the index of a character that is offset from the given index by the specified code points.
Syntax of offsetByCodePoints() Method:
int index = sb.offsetByCodePoints(3, 4);
The above statement will return the index of a character that is 4 code points away from the character present at index 3.
offsetByCodePoints() Description
public int offsetByCodePoints(int index, int codePointOffset): Returns the index of a character that is specified code points away from the character present at the given index.
offsetByCodePoints() Parameters
It takes two parameters:
- index: Gives the starting position. Integer index value that specifies a char in sequence. The offset count starts from here.
- codePointOffset: It is the integer offset value in code points.
offsetByCodePoints() Return Value
- Returns an index of character in the sequence represented by objected of StringBuilder class.
It throws IndexOutOfBoundsException
, if any of the following condition occurs:
- If
index < 0 or > sb.length()
- If
codePointOffset
is positive andindex + codePointOffset > sb.length()
- If
codePointOffset
is negative andindex + codePointOffset < 0
Also Read: StringBuilder in Java
Example 1: Finding index of an offset character
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Welcome"); //starting index 0, offset 2 int index = sb.offsetByCodePoints(0,2); //Index of char that is 2 code points away from first char System.out.println("Index of offset char: "+index); } }
Output:
Example 2: If codePointOffset is negative
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Welcome"); //starting index 5, offset -2 int index = sb.offsetByCodePoints(5,-2); System.out.println("Index of offset char: "+index); } }
Output:
Example 3: If index + codePointOffset is greater than the length of Sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Welcome"); //starting index 5, offset 5 int index = sb.offsetByCodePoints(5,5); System.out.println("Index of offset char: "+index); } }
Output: