StringBuilder insert() char array len in Java

insert(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

StringBuilder java.lang.StringBuilder.insert(int index, char[] str, int offset, int len)

This method takes four arguments, one of type char array and the other three are of type int as its parameters. This method inserts the string representation of a subarray of the array argument into this sequence. The subarray begins at the specified offset and extends len chars. The characters of the subarray are inserted into this sequence at the position indicated by the index.

Note: The length of this sequence increases by len chars.

Parameters: Four parameters are required for this method.

index: position at which to insert the subarray.

str: A char array.

offset: the index of the first char in subarray to be inserted.

len: the number of chars in the subarray to be inserted.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if index is negative or greater than length(), or offset or len are negative, or (offset+len) is greater than str.length.

Approach 1: When the index is in the range.

Java

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

        StringBuilder str = new StringBuilder("Hello World");
        // insert char array with len
        int offset = 0;
        int index = 3;
        char arr2[] = { 'X''Y''Z''P''Q''W''M' };
        int len = 2;
        str.insert(index, arr2, offset, len);
        System.out.println(str);
    }
}

Output:

HelXYlo World


Approach 2: When the index is out of range.

Java

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

        StringBuilder str = new StringBuilder("Hello World");
        // insert char array with len
        int offset = 0;
        int index = -1;
        char arr2[] = { 'X''Y''Z''P''Q''W''M' };
        int len = 2;
        str.insert(index, arr2, offset, len);
        System.out.println(str);
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: offset -1, length 11 at java.base/java.lang.String.checkOffset(String.java:3704) at java.base/java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:1102) at java.base/java.lang.StringBuilder.insert(StringBuilder.java:312)


No comments:

Post a Comment