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