StringBuffer insert() char Array len in Java

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

Syntax:

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

This method takes four arguments, first of type int , second of type char array , and rest two are of type int as its parameters. This method inserts the string representation of a subarray of the str 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 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 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 tobe 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.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int offset = 4

int index = 3

char arr2[] = { 'X', 'Y', 'Z', 'P', 'Q', 'W', 'M' }

int len = 2

str.insert(index, arr2, offset, len) = > It returns HelQWlo World.

Approach 1: When the index is in the range.

Java

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

        StringBuffer str = new StringBuffer("Hello World");
        // insert char array with len
        int offset = 4;
        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:

HelQWlo World


Approach 2: When the index is out of range.

Java

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

        StringBuffer str = new StringBuffer("Hello World");
        // insert char array with len
        int offset = 4;
        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.StringBuffer.insert(StringBuffer.java:531)


No comments:

Post a Comment