StringBuffer replace() Method in Java with Examples
The StringBuffer.replace() is the inbuilt method which is used to replace the characters in a substring of this sequence with the characters in the specified String. Here simply the characters in the substring are removed and other char is inserted at the start.
public StringBuffer replace(int first, int last, String st)
Parameters : The method accepts three parameters.
- first : This is of integer type which refers to the starting index.
- last : This is of integer type which refers to the ending index.
- st : This is of string type which refer to the String that will replace previous contents.
Return Value : The method returns this object after performing the above mentioned operations.
Exception : If the first is negative, greater than length(), or greater than last then StringIndexOutOfBoundsException.
Input: StringBuffer= "The first planet of solar system is merrhxy" first = 39 last = 42 st = "cur" Output: The first planet of solar system is mercury
Below programs illustrate the java.lang.StringBuffer.replace() method:
string buffer = Welcome to Geekshssgeeks After replacing string buffer= Welcome to Geekforsgeeks
Program 2: When negative index is passed:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -15 at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14)
Program 3: When index passed is greater than length
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start > length() at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:853) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.