How to use replaceAll() method in StringBuffer?

Ashokkumar Kandaswamy picture Ashokkumar Kandaswamy · Nov 23, 2015 · Viewed 9.4k times · Source

I need to replace multiple words in a string buffer. So I am looking for a replaceAll method in StringBuffer.

So do we have it in StringBuffer?

String method:

str2 = str1.replaceAll(regex, substr);
// (This is String method, I need like this in StringBuffer)

Answer

Chriki picture Chriki · Nov 23, 2015

There is no such method on StringBuffer. Perhaps the following will help:

StringBuffer str1 = new StringBuffer("whatever");
// to get a String result:
String str2 = str1.toString().replaceAll(regex, substr);
// to get a StringBuffer result:
StringBuffer str3 = new StringBuffer(str2);