StringBuilder offsetByCodePoints() in Java

offsetByCodePoints(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

int java.lang.AbstractStringBuilder.offsetByCodePoints(int index, int codePointOffset)

This method takes two arguments of type int as its parameters. This method returns the index within this sequence that is offset from the given index by codePointOffset code points.

Parameters: Two parameters are required for this method.

index: the index to be offset.

codePointOffset: the offset in code points.

Returns: the index within this sequence.

Throws:

IndexOutOfBoundsException - if the index is negative or larger than the length of this sequence,or if codePointOffset is positive and the subsequence starting with index has fewer than codePointOffset code points,or if codePointOffset is negative and the subsequence before index has fewer than the absolute value of codePointOffset code points.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int index = 3

int codePointOffset = 4

str.offsetByCodePoints(index,codePointOffset) = > It returns 7.

Approach 1: When the index is in the range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 3;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index, codePointOffset));

    }
}

Output:

7


Approach 2: When the index is out of range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = -1;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index, codePointOffset));

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.lang.AbstractStringBuilder.offsetByCodePoints(AbstractStringBuilder.java:472) at java.base/java.lang.StringBuilder.offsetByCodePoints(StringBuilder.java:85)


No comments:

Post a Comment