本文介绍了为什么不替换这行代码中的所有工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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

weatherLocation still contains "like in"

推荐答案

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

Strings are immutable. String#replaceAll() method will create a new string. You need to re-assign the result back to the variable:

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

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

Now, since the replaceAll method returns the modified string, you can also chain multiple replaceAll call in single line. In fact, you don't need a replaceAll() here. It is required, when you want to replace substring matching a regex pattern. Simply use String#replace() method:

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

这篇关于为什么不替换这行代码中的所有工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 13:46