Search code examples
javastringreplacecommand

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


Solution

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