无法使用replaceAll从字符串中删除单词

时间:2013-07-09 16:13:06

标签: java android

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]

我做错了什么?

4 个答案:

答案 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)

Stringimmutable。因此,String.replaceAll会返回instance的新String。所以你需要使用如下

weatherLocation = weatherLocation.replaceAll("how","")
                .replaceAll("what","")
                .replaceAll("weather", "")
                .replaceAll("like", "")
                .replaceAll(" in", "")
                .replaceAll(" at", "")
                .replaceAll("around", "");