Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string.replace(old, new) count how many replaced?

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);

            }

My console image

like image 703
donemanuel Avatar asked Sep 01 '25 16:09

donemanuel


1 Answers

Your currently accepted answer has few problems.

  1. It will need to iterate from beginning of string every time you invoke replaceFirst so it is not very efficient.

  2. 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:

    • after first iteration "abbb" will become"abb"
    • then in next iteration "abb" will become"ab"
    • and then "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
like image 72
Pshemo Avatar answered Sep 04 '25 09:09

Pshemo