Sto*_*rch 1 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;
}
Run Code Online (Sandbox Code Playgroud)
这出来:
5VT7N16324000434
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种方法可以使用数组和这样的循环来缩短这个:
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;
Run Code Online (Sandbox Code Playgroud)
在运行两者之后,第一个例子做我需要的,但第二个例子没有.它输出:
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
5VT7N16324000434 device
Run Code Online (Sandbox Code Playgroud)
我的第二个例子可能吗?为什么不起作用?
小智 6
试试这样.因为String是不可变对象.
for (String remove : array){
input = input.replace(remove, "");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |