How to remove a specified string using StringBuffer?

To remove a specific substring from a string, you can use the replace method of StringBuffer. Here is an example:

StringBuffer sb = new StringBuffer("Hello World");
String strToRemove = "World";

int index = sb.indexOf(strToRemove);
while (index != -1) {
    sb.replace(index, index + strToRemove.length(), "");
    index = sb.indexOf(strToRemove, index);
}

System.out.println(sb.toString());

The code above will output “Hello”, removing the specified string “World”. A while loop is used here to repeatedly remove the specified string until it no longer exists in the string.

bannerAds