我在 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”将在示例字符串中至少出现一次,但可能会多次出现在该文本中,偏移量将决定替换哪一个(并不总是第二个)。因此需要替换的字符串始终是偏移量处的字符串。
最佳答案
你可以这样做的一种方式..
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"
关于java - 替换字符串中的重复子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794908/