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

时间:2017-02-16 02:45:14

标签: 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 *", "");
    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

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

2 个答案:

答案 0 :(得分:6)

试试这样。因为String是不可变对象。

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

答案 1 :(得分:2)

Basiclly,string.replace不会更改原始字符串。你可以尝试

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