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

时间:2013-06-25 11:38:20

标签: java string

    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仍包含“like in”

4 个答案:

答案 0 :(得分:12)

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

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

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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

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

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

相关问题