gpt4 book ai didi

Java string.replace(old, new) 算多少个被替换?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:50 25 4
gpt4 key购买 nike

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

(如果代码只将 a 替换为 b 一次,则值为 1,但如果将 a 替换为 b 两次,则值为 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);

}

My console image

最佳答案

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

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(old, new) 算多少个被替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17218661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com