2013-06-29 189 views
2

子字符串的所有出现我有这个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。我哪里错了?

+3

你为什么不只是使用'.lastIndexOf()'找到最后发生? – fge

+0

如果有两个以上,它出错了吗?我想在指定的索引 – user2133404

回答

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()); 
+0

替换子字符串那么如何修改代码,以便只有指定的部分被替换? – user2133404