【问题标题】:Replace repeating substring in string替换字符串中的重复子字符串
【发布时间】:2014-11-05 20:13:59
【问题描述】:

我在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 函数之外,还有更好的方法吗?

编辑-

文本“字符串”将至少在示例字符串中出现一次,但可能在该文本中出现多次,偏移量将决定哪个被替换(并不总是第二个)。所以需要被替换的字符串总是偏移处的那个。

【问题讨论】:

  • 您是否只是想有效地制作“这是一个用于替换的示例字符串,这是一个更大的字符串与其他字符串”,或者您是否正在寻找一种方法来替换“字符串”的特定实例未知字符串?
  • 为了解决“用替换字符串替换从源字符串的偏移量N开始的M字符”的问题,我会说不——据我所知,没有比substring 更好的方法了。除非 Apache Commons 或其他第三方库中有什么东西。

标签: java regex string replace substring


【解决方案1】:

使用 indexOf() 的重载版本,它将起始索引作为第二个参数:

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

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

【讨论】:

    【解决方案2】:

    你可以使用

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

    而不是您的偏移量,并且仍然使用您的子字符串来替换它。

    【讨论】:

      【解决方案3】:

      尝试以下方法:

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

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

      【讨论】:

        【解决方案4】:

        一种方法可以做到这一点..

        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"
        

        【讨论】: