StringBuilder codePointCount() in Java

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

Syntax:

int java.lang.AbstractStringBuilder.codePointCount(int beginIndex, int endIndex)

This method takes two arguments of type int as its parameters. This method returns the number of Unicode code points in the specified text range of this sequence. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1.

Parameters: Two parameters are required for this method.

beginIndex: the index to the first char of the text range.

endIndex: the index after the last char of the text range.

Returns: the number of Unicode code points in the specified text range.

Throws:

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this sequence, or beginIndex is larger than endIndex.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int beginIndex = 2, endIndex = 5

str.codePointCount(beginIndex,endIndex ) = > It returns 3.

Approach 1: When the index is in the range.

Java

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

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

        int beginIndex = 2, endIndex = 5;
        System.out.println(str.codePointCount(beginIndex, endIndex));
    }
}

Output:

3


Approach 2: When the index is out of range.

Java

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

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

        int beginIndex = 6, endIndex = 5;
        System.out.println(str.codePointCount(beginIndex, endIndex));
    }
}


Output:

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


No comments:

Post a Comment