ReplaceAll方法替换java中的String数组

时间:2016-03-01 07:16:33

标签: java arrays replaceall

我有一个String数组:"11456811193903(admin 2016-03-01 11:16:23) (Sale)",我想从数组" (Sale)"中删除String。如何在Strings

的数组中替换它
Original String:
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};

After replacing:
fileName:11456811193903(admin 2016-03-01 11:16:23)

2 个答案:

答案 0 :(得分:2)

Bahramdun的解决方案完美无缺,但如果您是Java 8流的粉丝,您可能想要使用它:

String[] fileName = {...};
fileName = Arrays.stream(fileName)
                 .map(s -> s.replace("(Sale)", ""))
                 .toArray(size -> new String[size]);

答案 1 :(得分:1)

您可以尝试这样做:如果您的数组有多个元素,那么您可以循环遍历数组,如下所示。如果它只是一个句子,那么您可以直接删除(Scale)并再次将其分配给String fileName

String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
for (int i = 0; i < fileName.length; i++) {
    fileName[i] = fileName[i].replaceAll("\\(Sale\\)", "");
}
System.out.println("fileName = " + Arrays.toString(fileName));

结果是:

fileName = [11456811193903(admin 2016-03-01 11:16:23)]