问题
I have my console (image down below), and I have a command that will replace all oldstinrg to newstring. But how do I count how many of those were replaced?
(If the code replaced only once a to b then it will be 1, but if it replaced a to b twice the value would be 2)
(this is just a part of code, but no other part is needed or any how related to this part of code)
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);
}

回答1:
you could use String.replaceFirst and count it yourself:
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);
回答2:
Your currently accepted answer has few problems.
- It will need to iterate from beginning of string every time you invoke
replaceFirst
so it is not very efficient. But more importantly it can return "unexpected" results. For instance when we want to replace
"ab"
with"a"
, for string"abb"
method instead of1
will return as result2
matches. It happens because:- after first iteration
"abb"
becomes"ab"
"ab"
can be matched again which will be matched and replaced again.
In other words after replacements
"ab"->"b"
"abb"
will evolve into"a"
.- after first iteration
To solve those problems and get replacements count in one iteration you can use Matcher#appendReplacement
and Matcher#appendTail
methods like
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);
来源:https://stackoverflow.com/questions/17218661/java-string-replaceold-new-count-how-many-replaced