Java 使用循环从字符串中删除特定字符串

Java 使用循环从字符串中删除特定字符串,java,arrays,for-loop,Java,Arrays,For Loop,我目前正在尝试从字符串中删除特定的子字符串。我使用了多个变量,如下所示: public static String Replace(String input) { String step1 = input.replace("List of devices attached", ""); String step2 = step1.replace("* daemon not running. starting it now on port 5037 *", ""); St

我目前正在尝试从字符串中删除特定的子字符串。我使用了多个变量,如下所示:

 public static String Replace(String input) {

    String step1 = input.replace("List of devices attached", "");
    String step2 = step1.replace("* daemon not running. starting it now on port 5037 *", "");
    String step3 = step2.replace("* daemon started successfully *", "");
    String step4 = step3.replace(" ", "");
    String step5 = step4.replace("device", "");
    String step6 = step5.replace("offline", "");
    String step7 = step6.replace("unauthorized", "");

    String finished = step7;

    return finished;

}
这表明:

5VT7N16324000434
我想知道是否有一种方法可以通过使用数组和类似这样的循环来缩短这段时间:

public static String Replace(String input) {


    String[] array = {"List of devices attached",
            "* daemon not running. starting it now on port 5037 *",
            "* daemon started successfully *",
            " ",
            "device",
            "offline",
            "unauthorized"};

    for (String remove : array){

        input.replace(remove, "");

    }

    String output = input;

    return output;
在运行了这两个示例之后,第一个示例满足了我的需要,但第二个示例不满足。它输出:

List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
5VT7N16324000434    device

我的第二个例子可能吗?为什么不起作用?

像这样试试。因为字符串是不可变的对象

for (String remove : array){
    input = input.replace(remove, "");
}

像这样试试。因为字符串是不可变的对象

for (String remove : array){
    input = input.replace(remove, "");
}

基本上,string.replace不会更改原始字符串。你可以试试

for (String remove : array){
    input = input.replace(remove, "");
}

基本上,string.replace不会更改原始字符串。你可以试试

for (String remove : array){
    input = input.replace(remove, "");
}

谢谢,成功了。真不敢相信我忘了申报变量谢谢,它成功了。真不敢相信我忘了声明变量