Java StringBuffer example to replace the string or word in a StringBuffer at the specified position
By candid | Posted :
Nov 10, 2016
| Updated :
Nov 11, 2016
public StringBuffer replace(int start,int end,String str)
Replaces the characters in a substring of this sequence with characters in the specified String. 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. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)
Program:
package com.candidjava;
public class StringBufferRepalce
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Student");
sb.replace(3, 7, "Name");
System.out.println(sb);
}
}
Output:
StuName
Description:
Here the given string is replaced with the StringBuffer.
Parameters:
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.