且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java string.replace(旧,新)计数替换了多少?

更新时间:2023-12-03 20:23:04

您可以使用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);