为什么不替换这行代码中的所有工作?

String weatherLocation = weatherLoc[1].toString(); weatherLocation.replaceAll("how",""); weatherLocation.replaceAll("weather", ""); weatherLocation.replaceAll("like", ""); weatherLocation.replaceAll("in", ""); weatherLocation.replaceAll("at", ""); weatherLocation.replaceAll("around", ""); test.setText(weatherLocation); 

weatherLocation仍然包含“喜欢”

字符串是不可变的。 String#replaceAll()方法将创建一个新字符串。 您需要将结果重新分配回变量:

 weatherLocation = weatherLocation.replaceAll("how",""); 

现在,由于replaceAll方法返回修改后的字符串,您还可以在单​​行中链接多个replaceAll调用。 实际上,这里不需要replaceAll() 。 当你想要替换匹配正则表达式模式的子串时,它是必需的。 只需使用String#replace()方法:

 weatherLocation = weatherLocation.replace("how","") .replace("weather", "") .replace("like", ""); 

正如Rohit Jain所说,字符串是不变的; 在您的情况下,您可以链接调用replaceAll以避免多重影响。

 String weatherLocation = weatherLoc[1].toString() .replaceAll("how","") .replaceAll("weather", "") .replaceAll("like", "") .replaceAll("in", "") .replaceAll("at", "") .replaceAll("around", ""); test.setText(weatherLocation); 

正如Rohit Jain所说,而且,因为replaceAll采用正则表达式,而不是链接电话,你可以简单地做一些像

 test.setText(weatherLocation.replaceAll("how|weather|like|in|at|around", "")); 

我认为如果你需要在文本中替换很多字符串,最好使用StringBuilder / StringBuffer 。 为什么? 正如Rohit Jain所写, String是不可变的,因此每次调用replaceAll方法都需要创建新对象。 与String不同, StringBuffer / StringBuilder是可变的,因此它不会创建新对象(它将在同一个对象上工作)。

您可以在此Oracle教程http://docs.oracle.com/javase/tutorial/java/data/buffers.html中阅读有关StringBuilder的信息。