StringBuilder getChars() in Java

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

Syntax:

void java.lang.AbstractStringBuilder.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

This method takes four arguments one of type char array and the other three are of type int as its parameters. Characters are copied from this sequence into the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1.

Note: The total number of characters to be copied is srcEnd-srcBegin.

The characters are copied into the subarray of dst starting at index dstBegin and ending at index: dstbegin +(srcEnd-srcBegin) - 1

Parameters: Four parameters are required for this method.

srcBegin: start copying at this offset.

srcEnd: stop copying at this offset.

dst: the array to copy the data into.

dstBegin:  offset into dst.

Throws:

StringIndexOutOfBoundsException - if any of the following is true:

1. srcBegin is negative.

2. dstBegin is negative.

3. the srcBegin argument is greater thanthe srcEnd argument.

4. srcEnd is greater than this.length().

5. dstBegin+srcEnd-srcBegin is greater than dst.length

Approach 1: When the indexes are in the range.

Java

import java.util.Arrays;

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

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

        int srcBegin = 2, srcEnd = 8;
        char dst[] = { 'a''b''c''l''o''W' };
        int dstBegin = 0;
        str.getChars(srcBegin, srcEnd, dst, dstBegin);

        System.out.println(Arrays.toString(dst));
    }
}

Output:

[l, l, o,  , W, o]


Approach 2: When the indexes are out of range.

Java

import java.util.Arrays;

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

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

        int srcBegin = 10, srcEnd = 8;
        char dst[] = { 'a''b''c''l''o''W' };
        int dstBegin = 0;
        str.getChars(srcBegin, srcEnd, dst, dstBegin);

        System.out.println(Arrays.toString(dst));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 8, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.getChars(AbstractStringBuilder.java:508) at java.base/java.lang.StringBuilder.getChars(StringBuilder.java:85)


No comments:

Post a Comment