我有我的控制台(下面的图像),我有一个命令,将所有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);
}
Run Code Online (Sandbox Code Playgroud)

我有一个像控制台这样的小程序,允许通过JTextField输入命令.
我有很多命令写入输入转换为字符串>如果命令有ping一个IP属性(ping 192.168.1.1)我substring 5(ping),但现在我想要几个属性,如(命令atr1 art22 atr333 art4444)我会得到的
String command = "command"; //I can make this one
String attribute1 = "atr1"; //I can make this one
String attribute2 = "atr22";
String attribute3 = "atr333";
Run Code Online (Sandbox Code Playgroud)
等等,但是无论长度属性如何它都会给我...因为我可以用子串完成所有事情,但是它会定义长度!
我如何制作一个不需要对象的方法,但如果有的话,它会使用它!
像这样
void cls(String source){
if(source.isEmpty()){
source = "Unknown source";
}
output.setText("Screen cleared from " + source);
}
Run Code Online (Sandbox Code Playgroud)
后来当我打电话给我时我能做到
cls();
Run Code Online (Sandbox Code Playgroud)
但它会抛出一个错误,因为它需要一个字符串
cls("string");
Run Code Online (Sandbox Code Playgroud)
但我希望两者都能奏效!