I am working in java and I want to take the following string:
String sample = "This is a sample string for replacement string with other string";
And I want to replace second "string" with "this is a much larger string", after some java magic the output would look 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 the offset of where the text starts. In this case, 40 and the text getting replaced "string".
I could do a:
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 other then using substring java functions?
EDIT -
The text "string" will be in the sample string at least once, but could be in that text numerous times, that the offset would dictate which one gets replaced (not always the second). So the string that needs to get replaced is always the one at the offset.
substringthat I know of. Unless there's something in Apache Commons or some other third-party library.