替换字符串中的重复子串

3
我正在使用Java编程,我想要获取以下字符串:
String sample = "This is a sample string for replacement string with other string";

我想把第二个 "string" 替换为 "this is a much larger string",经过一些 Java 魔法,输出将会是这样的:
System.out.println(sample);
"This is a sample string for replacement this is a much larger string with other string"

我有文本开始的偏移量。在这种情况下,偏移量为40,被替换的文本是“string”。
我可以执行以下操作:
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的substring函数,还有更好的方法吗?
编辑 -
文本“string”至少会在示例字符串中出现一次,但可能会在该文本中多次出现,偏移量将决定哪个被替换(不总是第二个)。因此需要替换的字符串始终是偏移量处的字符串。

你是想要高效地生成"This is a sample string for replacement this is a much larger string with other string"这个字符串,还是在一个未知的字符串中替换特定的"string"实例? - Theopile
1
为了解决“将源字符串偏移量为N的_M_个字符替换为替换字符串”的问题,我认为没有比我所知道的substring更好的方法。除非在Apache Commons或其他第三方库中有什么东西。 - ajb
4个回答

2
尝试以下步骤:
sample.replaceAll("(.*?)(string)(.*?)(string)(.+)", "$1$2$3this is a much larger string$5");

$1 表示第一个被括号捕获的组在第一个参数中。


2

你可以采取的一种方式是...


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"

2
使用重载版本的indexOf(),它接受起始索引作为第二个参数:
str.indexOf("string", str.indexOf("string") + 1);

获取两个字符串的索引...然后用该偏移量替换它...希望这有所帮助。


1
你可以使用


str.indexOf("string", str.indexOf("string") + 1);

使用你的子字符串替换偏移量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接