0
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]时,这很有效

我究竟做错了什么?

4

4 回答 4

1

您需要将方法调用返回的值分配回 String 引用变量。每次执行时replaceAll(),它都会返回一个 String对象,但您的weatherLocation变量仍引用原始字符串。

  weatherLocation = weatherLocation.replaceAll("how","")
                    .replaceAll("what","")
                    .replaceAll("weather", "")
                    .replaceAll("like", "")
                    .replaceAll(" in", "")
                    .replaceAll(" at", "")
                    .replaceAll("around", "");
于 2013-07-09T16:14:13.783 回答
0

字符串是不可变的。您需要将所有这些 replaceAll 调用的值分配给一个变量,这就是您想要的。

weatherLocation = weatherLocation.replaceAll("how","")
                .replaceAll("what","")
                .replaceAll("weather", "")
                .replaceAll("like", "")
                .replaceAll(" in", "")
                .replaceAll(" at", "")
                .replaceAll("around", "");
于 2013-07-09T16:14:11.853 回答
0

试试这个:

weatherLocation = weatherLocation.replaceAll("how","")
                        .replaceAll("what","")
                        .replaceAll("weather", "")
                        .replaceAll("like", "")
                        .replaceAll(" in", "")
                        .replaceAll(" at", "")
                        .replaceAll("around", "");
于 2013-07-09T16:14:26.723 回答
0

Stringimmutable。所以String.replaceAll返回一个新instanceString. 所以你需要像下面这样使用

weatherLocation = weatherLocation.replaceAll("how","")
                .replaceAll("what","")
                .replaceAll("weather", "")
                .replaceAll("like", "")
                .replaceAll(" in", "")
                .replaceAll(" at", "")
                .replaceAll("around", "");
于 2013-07-09T16:14:36.743 回答