简体   繁体   English

替换字符串中的重复子字符串

[英]Replace repeating substring in string

I am working in java and I want to take the following string: 我在java工作,我想采取以下字符串:

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: 我想用“这是一个更大的字符串”替换第二个“字符串”,在一些java魔术之后,输出看起来像这样:

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". 在这种情况下,40和文本被替换为“字符串”。

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? 但除了使用子串java函数之外,还有更好的方法吗?

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). 文本“string”将在示例字符串中至少一次,但可能在该文本中多次,偏移将指示哪一个被替换(不总是第二个)。 So the string that needs to get replaced is always the one at the offset. 因此需要替换的字符串始终是偏移量的字符串。

Use overloaded version of indexOf(), which takes the starting indes as 2nd parameter: 使用indexOf()的重载版本,它将起始indes作为第二个参数:

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

To get the index of 2 string ... and then replace it with this offset ... Hopefully this helps. 要获得2个字符串的索引...然后用这个偏移量替换它...希望这会有所帮助。

Try the following: 请尝试以下方法:

sample.replaceAll("(.*?)(string)(.*?)(string)(.+)", "$1$2$3this is a much larger string$5");

$1 denotes the first group captured inside parentheses in the first argument. $1表示第一个参数中括号内捕获的第一个组。

One way you could 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"

You could use 你可以用

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

instead of your offset, and still use your substring to replace it. 而不是你的偏移量,仍然使用你的子串替换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM