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
。我哪里错了?
你为什么不只是使用'.lastIndexOf()'找到最后发生? – fge
如果有两个以上,它出错了吗?我想在指定的索引 – user2133404