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

限于喜欢 提交于 2019-12-23 19:41:56

问题


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.

  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 "abb" method instead of 1 will return as result 2 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".


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!