seno71625 seno71625 - 10 days ago 7
Java Question

Replace a substring at a particular position in a string in Java

Following is my string variable :

String str = "Home(om), Home(gia)";


I want to replace the substring
om
present between
()
with
tom
.

I am able to find the index of
()
in which
om
is present, but the following will not work :

int i1 = str.indexOf("(");
int i2 = str.indexOf(")");

str = str.replace(str.substring(i1+1,i2),"tom");


I require the result as
Home(tom), Home(gia)
.

How to do this?

ajb ajb
Answer

I would not use any replace() method if you know the indexes of the substring you want to replace. The problem is that this statement:

str = str.replace(str.substring(someIndex, someOtherIndex), replacement);

first computes the substring, and then replaces all occurrences of that substring in the original string. replace doesn't know or care about the original indexes.

It's better to just break up the string using substring():

int i1 = str.indexOf("(");
int i2 = str.indexOf(")");

str = str.substring(0, i1+1) + "tom" + str.substring(i2);
Comments