Java string.replace(旧,新)计数替换了多少? [英] Java string.replace(old, new) count how many replaced?

查看:70
本文介绍了Java string.replace(旧,新)计数替换了多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的控制台(下图),并且我有一个命令将所有oldstinrg替换为newstring.但是我如何计算其中有多少被替换了?

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?

(如果代码仅将a替换为b,那么它将为1,但是如果将a替换为b的值将为2,则为2)

(这只是代码的一部分,但不需要其他部分或与代码的这一部分有任何关联)

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

            }

推荐答案

您可以使用String.replaceFirst自己计算:

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

这篇关于Java string.replace(旧,新)计数替换了多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆