Vishwanath.M Vishwanath.M - 6 months ago 8
Java Question

Replace duplicate word in a string one by one

Hi am having string like below

String str = "vishwa sgsu shishs sjishs vishwa sjsjos vishwa";

I have to replace each occurrence like below


  1. vishwa with xyz

  2. vishwa with yzk

  3. vishwa with jey



So my result string will look like below

"xyz sgsu shishs sjishs yzk sjsjos jey"

I tried with replaceFirst(), replace() methods, but not working.

How can i do it.?

Answer

Please use below code and check your output.

  String str = "vishwa sgsu shishs sjishs vishwa sjsjos vishwa";

  String strNewString = str.replace("vishwa","xyz");
  strNewString = strNewString.replace("vishwa","yzk");
  strNewString = strNewString.replace("vishwa","jey");

Now use strNewString as future use.

Comments