1

I'm currently trying to remove specific sub-strings from a string. I have done it using multiple variables like below:

 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;

}

This out puts:

5VT7N16324000434

Im wondering if there is a way that could shorten this using an array and a loop of sorts like this:

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;

after running both, the first example does what I need, but the second does not. It outputs:

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

Is my second example possible? Why doesn't it work?

CrazyCoder
  • 389,263
  • 172
  • 990
  • 904
Stone Monarch
  • 325
  • 2
  • 15

2 Answers2

6

try like this. Because String is immutable object.

for (String remove : array){
    input = input.replace(remove, "");
}
Naros
  • 19,928
  • 3
  • 41
  • 71
Luong Dinh
  • 569
  • 4
  • 17
2

Basiclly, string.replace doesn't change the origin string. you can try

for (String remove : array){
    input = input.replace(remove, "");
}
Aaric Chen
  • 1,138
  • 11
  • 12