Java StringBuilder replace() Method Example

Java StringBuilder replace(int start, int end, String str) method 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 the start. (This sequence will be lengthened to accommodate the specified String if necessary.)

Java StringBuilder lastIndexOf() Method Example

Example to replace the string "ja" with string "java" using replace() method.
public class ReplaceExample {
 public static void main(String[] args) {
  StringBuilder buffer = new StringBuilder("jaguides");
  
  // replace ja with java- start index 0 and end index -1
  StringBuilder subBuffer = buffer.replace(0, 2, "java");
  
  System.out.println(subBuffer);
 }
}
Output:
javaguides

Reference




Comments