java无法使用replaceAll从字符串中删除单词
if(containsAllWeather || containsAllWeather2){
String weatherLocation = value.toString();
if (weatherLocation != null){
weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
}
weatherLocation仍然准确地给出变量值包含的内容,并且不会删除上面列出的任何单词
当我将weatherLocation拆分为一个字符串数组(比如weatherLoc数组)时,这些代码行对weatherLoc起作用[1]
我做错了什么
# 1 楼答案
字符串是不可变的。您需要将所有这些replaceAll调用的值分配给一个变量,这就是您想要的
# 2 楼答案
String
是immutable
。因此String.replaceAll
返回一个新的instance
{# 3 楼答案
试试这个:
# 4 楼答案
您需要将方法调用返回的值分配回字符串引用变量。每次执行
replaceAll()
操作时,它都会返回一个新的String
对象,但weatherLocation
变量仍在引用原始字符串