seno71625 seno71625 - 1 year ago 101
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
present between

I am able to find the index of
in which
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download