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);
}
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 "abbb"
accepted solution instead of 1
will return 3
matches. It happens because:
"abbb"
will become"abb"
"abb"
will become"ab"
"ab"
will become "a"
.So since we had 3 iterations counter
will be 3
and that is the value which would be returned instead of 1
which is correct result.
To avoid this kind of problems and count only valid replacements in original string we can use Matcher#appendReplacement
and Matcher#appendTail
.
Demo:
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);
Result:
ab abb
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With