StringBuffer replace() in Java

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

Syntax:

StringBuffer java.lang.StringBuffer.replace(int start, int end, String str)

This method takes three arguments, two are of type int and one of type String as its parameters. This method replaces the characters in a substring of this sequence with characters in the specified String.

Note: The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.

Parameters: Three parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

str: String that will replace previous contents.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

For Example:

StringBuffer str = new StringBuffer("Hello World")

int start = 2, end = 7

String str1 = "ABCABC"

str.replace(start, end, str1) = > It returns HeABCABCorld.

Approach 1: When the index is in the range.

Java

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

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

        int start = 2, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}

Output:

HeABCABCorld


Approach 2: When the index is out of range.

Java

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

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

        int start = -1, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start -1, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:995) at java.base/java.lang.StringBuffer.replace(StringBuffer.java:491)


No comments:

Post a Comment