4

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?

2
  • whar is expected output ? Commented Nov 26, 2016 at 6:01
  • What are other potential inputs/outputs? It's unclear what exactly you want this code to do given a different str. Commented Nov 26, 2016 at 6:41

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use regex with replaceAll

String str = "Home(om)";

str = str.replaceAll("[(].*[)]", "(tom)");
System.out.println(str);

Output:

Home(tom)

[(] : look for (

.* : capture all except line break mean \n\r

[)] : look for )

UPDATE :

You can use replaceFirst with non-greedy quantifier ?

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

    str = str.replaceFirst("([(](.*?)[)])", "(tom)");
    System.out.println(str);

Output:

Home(tom), Home(gia)

3 Comments

But this will not work in case of String str = "Home(om), Home(gia)";. It will give me the result Home(tom), Home(tom). I need Home(tom), Home(gia)
@seno71625 i agree but i thought you said I require the result in the form of Home(tom). any way let me try
@seno71625 Your question is a bit unclear... If you "require "Home(tom), Home(gia)"", I can do that: return "Home(tom), Home(gia)";

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.