2017-02-16 1 views
1

현재 문자열에서 특정 하위 문자열을 제거하려고합니다.루프를 사용하여 특정 문자열을 문자열에서 제거

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 

두 번째 예가 가능합니까? 왜 작동하지 않습니까?

답변

6

시도해보십시오. String은 변경 불가능한 객체이므로

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

감사합니다. 변수를 선언하는 걸 깜박하지 못했습니다. –

2

basiclly, string.replace는 원래 문자열을 변경하지 않습니다. 시도해 볼 수 있습니다

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