Java – replace duplicate substrings in string

I work in Java and I want to take the following string:

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

I want to replace the second "string" with "this is a larger string". After some Java magic, the output looks like this:

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

I do have an offset from the beginning of the text In this case, 40 and text are replaced with "string"

I can do one:

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 than using substring Java functions?

Edit –

The text "string" will be in the sample string at least once, but possibly more than once, and the offset will indicate which one is replaced (not always the second) Therefore, the string to be replaced is always the offset string

Solution

One way you can 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"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>