In this tutorial, we will discuss Java StringBuffer replace() method with the help of examples.
Syntax of replace() method:
//replace substring from index 4 to 9 by given string "hello" //4 is inclusive and 9 is exclusive sb.replace(4, 9, "hello");
replace() Description
public StringBuffer replace(int start, int end, String str): Replace the substring starting from start
index till end
index with the given string str
.
replace() Parameters
The replace() method of Java StringBuffer class takes three parameters:
- start: Represents the start of substring that is going to be replaced.
- end: Represents the end of the substring that is going to be replaced.
- str: This string is going to replace the substring marked by
start
andend
index.
replace Return Value
- Returns a StringBuffer object that contains the new string after replacement.
This method throws StringIndexOutOfBounds
Exception, if any of the following condition occurs:
- start index < 0
- start index > length of the string
Example 1: Replace a given string with another string
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello Guys"); System.out.println("Given Sequence : "+sb); //replace the substring sb.replace(6, 10, "World"); System.out.println("New Sequence: "+sb); } }
Output:
Example 2: If replace string is smaller than the given string
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("AnotherText"); System.out.println("Given Sequence: "+sb); sb.replace(0, sb.length(), "Text"); System.out.println("New Sequence: "+sb); } }
Output:
Example 3: If endIndex is greater than the length of given string
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("Given Sequence: "+sb); //end index is greater than original string length sb.replace(0, 100, "Hi"); System.out.println("New Sequence: "+sb); } }
Output:
Example 4: If startIndex is Negative
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Text"); //start index is negative sb.replace(-5, 10, "AnotherText"); System.out.println("String after replace: "+sb); } }
Output:
Leave a Reply