有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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]

我做错了什么


共 (4) 个答案

  1. # 1 楼答案

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

    weatherLocation = weatherLocation.replaceAll("how","")
                    .replaceAll("what","")
                    .replaceAll("weather", "")
                    .replaceAll("like", "")
                    .replaceAll(" in", "")
                    .replaceAll(" at", "")
                    .replaceAll("around", "");
    
  2. # 2 楼答案

    Stringimmutable。因此String.replaceAll返回一个新的instance{}。所以你需要像下面这样使用

    weatherLocation = weatherLocation.replaceAll("how","")
                    .replaceAll("what","")
                    .replaceAll("weather", "")
                    .replaceAll("like", "")
                    .replaceAll(" in", "")
                    .replaceAll(" at", "")
                    .replaceAll("around", "");
    
  3. # 3 楼答案

    试试这个:

    weatherLocation = weatherLocation.replaceAll("how","")
                            .replaceAll("what","")
                            .replaceAll("weather", "")
                            .replaceAll("like", "")
                            .replaceAll(" in", "")
                            .replaceAll(" at", "")
                            .replaceAll("around", "");
    
  4. # 4 楼答案

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

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