我有我的控制台(下面的图像),我有一个命令将所有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);
}
答案 0 :(得分: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);
答案 1 :(得分:4)
您的currently accepted answer几乎没有问题。
replaceFirst
时,都需要从字符串的开头进行迭代,因此效率不高。 但更重要的是,它可以返回“意外”的结果。例如,当我们要将"ab"
替换为"a"
时,对于字符串"abb"
,方法而不是1
将返回结果2
匹配。这是因为:
"abb"
成为"ab"
"ab"
可以再次匹配,将匹配并再次替换。 换句话说,替换后"ab"->"b"
"abb"
将演变为成"a"
。
要解决这些问题并在一次迭代中获得替换计数,您可以使用Matcher#appendReplacement
和Matcher#appendTail
方法,例如
String outtext = "Some text with word text and that will need to be " +
"replaced with another text x";
String repfrom = "text";
String repto = "[replaced word]";
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);