Java 为什么';你不能替换这行代码中的所有工作吗?

Java 为什么';你不能替换这行代码中的所有工作吗?,java,string,Java,String,weatherLocation仍然包含“like in”字符串是不可变的。方法将创建一个新字符串。您需要将结果重新分配回变量: String weatherLocation = weatherLoc[1].toString(); weatherLocation.replaceAll("how",""); weatherLocation.replaceAll("weather", ""); weatherLocation.replaceAll("like", ""); weatherLoc

weatherLocation仍然包含“like in”

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

    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);
现在,由于
replaceAll
方法返回修改后的字符串,您还可以在单行中链接多个
replaceAll
调用。实际上,这里不需要
replaceAll()
。当您要替换与正则表达式模式匹配的子字符串时,它是必需的。简单使用方法:


正如Rohit Jain所说,字符串是不可变的;在您的情况下,您可以将调用链接到
replaceAll
,以避免多次做作

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

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


例如,您可以在本Oracle教程中阅读StringBuilder。

正如Rohit Jain所说,而且,由于replaceAll采用正则表达式,而不是链接调用,因此您只需执行以下操作

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

另外,非常错误:)我的答案完全失败,是的--删除了它。问题是
StringBuffer
/
StringBuilder
没有
replaceAll
方法。当然,你是对的,但这并不意味着你不能在StringBuffer/StringBuilder中替换字符串。您可以使用
replace
方法。您可以使用
String weatherLocation = weatherLoc[1].toString()
        .replaceAll("how","")
        .replaceAll("weather", "")
        .replaceAll("like", "")
        .replaceAll("in", "")
        .replaceAll("at", "")
        .replaceAll("around", "");
test.setText(weatherLocation);
test.setText(weatherLocation.replaceAll("how|weather|like|in|at|around", ""));