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)

您当前接受的答案几乎没有问题。
每次调用时都需要从字符串的开头进行迭代replaceFirst,因此效率不是很高。
但更重要的是它可以返回“意外”的结果。例如,当我们想要替换"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)
你可以使用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)
| 归档时间: |
|
| 查看次数: |
4836 次 |
| 最近记录: |