我在
java工作,我想采取以下字符串:
String sample = "This is a sample string for replacement string with other string";
我想用“这是一个更大的字符串”替换第二个“字符串”,在一些java魔术之后,输出看起来像这样:
System.out.println(sample);
"This is a sample string for replacement this is a much larger string with other string"
我确实有文本开始的偏移量.在这种情况下,40和文本被替换为“字符串”.
我可以做一个:
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"
但除了使用子串java函数之外,还有更好的方法吗?
编辑 –
文本“string”将在示例字符串中至少一次,但可能在该文本中多次,偏移将指示哪一个被替换(不总是第二个).因此需要替换的字符串始终是偏移量的字符串.