Let’s learn String offsetByCodePoints(int index, int codePointOffset) method java.
String offsetByCodePoints(int index, int codePointOffset) method in java
String offsetByCodePoints(int index, int codePointOffset) method returns the index within this String that is offset from the given index by codePointOffset code points.
Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.
Syntax
public int offsetByCodePoints(int index, int codePointOffset)
Parameters
index the index to be offset.
codePointOffset the offset in code points.
Throws
IndexOutOfBoundsException – if index is negative or larger than the length of this String, or if codePointOffset is positive and the substring starting with index has fewer than codePointOffset code points, or if codePointOffset is negative and the substring before index has fewer than the absolute valueof codePointOffset code points.
Example
class StringOffSetByCodePointsMethod { public static void main(String[] args) { String s = "Hello World Java"; System.out.println("Given string : " + s); int value = s.offsetByCodePoints(1, 5); System.out.println("index : " + value); } }
Output:
Given string : Hello World Java
index : 6
offsetByCodePoints() method throws IndexOutOfBoundsException if codePointOffset is positive or negative and the index in the subsequence is smaller than the codePointOffset code point.
class StringOffSetByCodePointsMethod { public static void main(String[] args) { StringBuffer sb = new StringBuffer("HelloWorld"); System.out.println("Given string : " + sb); int index = sb.offsetByCodePoints(2, 10); System.out.println("Index of offset 2, 10 : " + index); } }
Output:
Given string : HelloWorld
Exception in thread “main” java.lang.IndexOutOfBoundsException
at java.base/java.lang.Character.offsetByCodePoints(Character.java:9615)
at java.base/java.lang.AbstractStringBuilder.offsetByCodePoints(AbstractStringBuilder.java:477)
at java.base/java.lang.StringBuffer.offsetByCodePoints(StringBuffer.java:279)
at ArraysInJava/com.Strings.java.StringOffSetByCodePointsMethod.main(StringOffSetByCodePointsMethod.java:9)
offsetByCodePoints() method throws IndexOutOfBoundsException if index is negative or greater than the length of the given sequence.
class StringOffSetByCodePointsMethod { public static void main(String[] args) { StringBuffer sb = new StringBuffer("HelloWorld"); System.out.println("Given string : " + sb); int index = sb.offsetByCodePoints(-4, 10); System.out.println("index of offset -4, 10 is: " + index); } }
Output:
Given string : HelloWorld
Exception in thread “main” java.lang.IndexOutOfBoundsException
at java.base/java.lang.AbstractStringBuilder.offsetByCodePoints(AbstractStringBuilder.java:475)
at java.base/java.lang.StringBuffer.offsetByCodePoints(StringBuffer.java:279)
at ArraysInJava/com.Strings.java.StringOffSetByCodePointsMethod.main(StringOffSetByCodePointsMethod.java:9)
Also read – encapsulation in java