我有这个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
。我哪里错了?
最佳答案
表达式
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());
关于java - 字符串替换替换java中所有出现的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17375527/