class StringBufferReplace{ public static void main(String[] args) { //Create StringBuffer object StringBuffer sb = new StringBuffer("This is a String"); System.out.println("Before: " + sb); /* public StringBuffer replace(int start, int end, String str): * It replaces the part of the content (substring starting from * index start and ending with index end-1) of StringBuffer with * the specified string "str" */ sb.replace(10,16,"TEXT"); System.out.println("After: " + sb); } }
Output:
Before: This is a String After: This is a TEXT
More about replace() method from javadoc:
public StringBuffer replace(int start, int end, String str)
: Replaces the substring of original string with the specified String. The substring begins at the specified index start and ends at index end – 1. 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.)
Parameters:
start – The beginning index, inclusive.
end – The ending index, exclusive.
str – String that will replace previous contents.
It throws:
StringIndexOutOfBoundsException – if start index is negative, greater than length(), or greater than specified index end.
Leave a Reply