Replace a duplicate substring in a string

I am working in java and want to take the following line:

String sample = "This is a sample string for replacement string with other string";

      

And I want to replace the second "line" with "this is much more than a line", after some java magic, the output will look like this:

System.out.println(sample);
"This is a sample string for replacement this is a much larger string with other string"

      

I have an offset where the text starts. In this case, 40 and the text are replaced with "string".

I could do:

int offset = 40;
String sample = "This is a sample string for replacement string with other string";
String replace = "string";
String replacement = "this is a much larger string";

String firstpart = sample.substring(0, offset);
String secondpart = sample.substring(offset + replace.length(), sample.length());
String finalString = firstpart + replacement + secondpart;
System.out.println(finalString);
"This is a sample string for replacement this is a much larger string with other string"

      

but is there a better way to do this and then use java substring functions?

EDIT -

The text "string" will be in the pattern line at least once, but it can be in this text many times that the offset will determine which one needs to be replaced (not always the second one). Thus, the string to be replaced is always the same as the string.

+3


source to share


4 answers


Use the overloaded version of indexOf () that takes starting indices as 2nd parameter:

str.indexOf("string", str.indexOf("string") + 1);

      



To get the index 2 of the row ... and then replace it with that offset ... Hope this helps.

+2


source


Try the following:

sample.replaceAll("(.*?)(string)(.*?)(string)(.+)", "$1$2$3this is a much larger string$5");

      



$1

denotes the first group, captured in parentheses in the first argument.

+2


source


One way to do this.

String s = "This is a sample string for replacement string with other string";
String r = s.replaceAll("^(.*?string.*?)string", "$1this is a much larger string");
//=> "This is a sample string for replacement this is a much larger string with other string"

      

+2


source


you can use

str.indexOf("string", str.indexOf("string") + 1);

      

instead of your offset and still use a substring to replace it.

+1


source







All Articles