Java string.replace(旧的,新的)算多少替换?

don*_*uel 3 java string command replace

我有我的控制台(下面的图像),我有一个命令,将所有oldstinrg替换为newstring.但我如何计算其中有多少被替换?

(如果代码只替换一次a到b那么它将是1,但如果它替换a到b两次,那么值将是2)

(这只是代码的一部分,但不需要其他部分或任何与此部分代码相关的内容)

else if(intext.startsWith("replace ")){


                String[] replist = original.split(" +");    

                String repfrom = replist[1];
                String repto = replist[2];

                lastorep = repfrom;
                lasttorep = repto;

                String outtext = output.getText();
                String newtext = outtext.replace(repfrom, repto);
                output.setText(newtext);

                int totalreplaced = 0; //how to get how many replaced strings were there?

                message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto);

            }
Run Code Online (Sandbox Code Playgroud)

我的控制台图片

Psh*_*emo 7

当前接受的答案几乎没有问题。

  1. 每次调用时都需要从字符串的开头进行迭代replaceFirst,因此效率不是很高。

  2. 但更重要的是它可以返回“意外”的结果。例如,当我们想要替换"ab""a", 对于字符串"abbb"接受的解决方案而不是1返回3匹配项。发生这种情况是因为:

    • 第一次迭代后将"abbb"变成"abb"
    • 那么在下一次迭代"abb"中将变成"ab"
    • 然后"ab"就会变成"a"

    因此,由于我们进行了 3 次迭代,counter因此3这就是将返回的值,而不是1正确的结果。


为了避免此类问题并仅计算原始字符串中的有效替换,我们可以使用和。演示:Matcher#appendReplacementMatcher#appendTail

String outtext = "abb abbb";
String repfrom = "ab";
String repto = "a";

Pattern p = Pattern.compile(repfrom, Pattern.LITERAL);
Matcher m = p.matcher(outtext);

int counter = 0;
StringBuffer sb = new StringBuffer();
while (m.find()) {
    counter++;
    m.appendReplacement(sb, repto);
}
m.appendTail(sb);

String newtext = sb.toString();

System.out.println(newtext);
System.out.println(counter);
Run Code Online (Sandbox Code Playgroud)

结果:

ab abb
2
Run Code Online (Sandbox Code Playgroud)


Phi*_*der 6

你可以使用String.replaceFirst并自己计算:

String outtext = output.getText();
String newtext = outtext;
int totalreplaced = 0;

//check if there is anything to replace
while( !newtext.replaceFirst(repfrom, repto).equals(newtext) ) {
    newtext = newtext.replaceFirst(repfrom, repto);
    totalreplaced++;
}

message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto);
Run Code Online (Sandbox Code Playgroud)