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仍然提供变量 value 所包含的内容,并且不会删除上面列出的任何单词。
当我将weatherLocation拆分为一个字符串数组时,例如,weatherLoc数组,以及那些为weatherLoc工作的代码行[1]
我做错了什么?
答案 0 :(得分:1)
您需要将方法调用返回的值分配回String引用变量。每次执行replaceAll()
时,它都会返回新 String
对象,但您的weatherLocation
变量仍然引用原始字符串。
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
答案 1 :(得分:0)
字符串是不可变的。您需要将所有这些replaceAll调用的值分配给变量,这将是您想要的。
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
答案 2 :(得分:0)
试试这个:
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
答案 3 :(得分:0)
String
是immutable
。因此,String.replaceAll
会返回instance
的新String
。所以你需要使用如下
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");