字符串替换替换java中出现的所有子字符串

时间:2013-06-29 00:32:44

标签: java

我有这个java代码

    String s3="10100111001";
    String s4="1001";
    String s5="0";
    System.out.println(s3);
    int last_index=3; //To replace only the last 

    while(last_index>=0) {
        last_index=s3.indexOf(s4,last_index);
        System.out.println("B:" +last_index);
        if(last_index>=0)
        {

            s3=s3.replace(s3.substring(last_index,(last_index+s4.length())),s5);
            last_index=last_index+s4.length();
            System.out.println("L:"+last_index);
            continue;
        }

        else
        {
            continue;
        }

    }
    System.out.println(s3);

理想情况下,此代码应仅替换1001的最后一次出现,但它会替换1001

的出现次数

我的输出为10010,但应为10100110。我哪里错了?

1 个答案:

答案 0 :(得分:0)

表达式

s3.substring(last_index,(last_index+s4.length()))

返回"1001"字符串。使用该字符串作为参数调用replace将在整个字符串中执行替换,因此它将替换两次出现。

要修复您的解决方案,您可以将replace的调用替换为三个子字符串的组合:

  • 从零到last_index
  • s5
  • last_index+4到最后。

像这样:

s3=s3.substring(0, last_index) + s5 + s3.substring(last_index+s4.length());