我有一个字符串列表,其中大多数是多个单词:
"how are you"
"what time is it"
我想从此列表中的每个字符串中删除空格:
"howareyou"
"whattimeisit"
我知道
Collections.replaceAll(list, to replace, replace with)
,但这仅适用于具有确切值的字符串,而不适用于每个字符串中的每个实例。 最佳答案
您必须将replace函数应用于列表中的每个字符串。
由于字符串是不可变的,因此您将不得不创建另一个列表,其中将存储没有空格的字符串。
List<String> result = new ArrayList<>();
for (String s : source) {
result.add(s.replaceAll("\\s+", ""));
}
不可变表示无法更改对象,如果要更改其状态,则必须创建一个新对象。
String s = "how are you";
s = s.replaceAll("\\s+", "");
如果您未将新字符串分配给变量s,则replaceAll函数将返回该字符串,但该字符串仍将包含空格。