This question already has answers here:
String replace method is not replacing characters
                                
                                    (5个答案)
                                
                        
                2年前关闭。
            
        

    String weatherLocation = weatherLoc[1].toString();
weatherLocation.replaceAll("how","");
weatherLocation.replaceAll("weather", "");
weatherLocation.replaceAll("like", "");
weatherLocation.replaceAll("in", "");
weatherLocation.replaceAll("at", "");
weatherLocation.replaceAll("around", "");
test.setText(weatherLocation);


weatherLocation仍然包含“喜欢”

最佳答案

字符串是不可变的。 String#replaceAll()方法将创建一个新字符串。您需要将结果重新分配回变量:

weatherLocation = weatherLocation.replaceAll("how","");


现在,由于replaceAll方法返回修改后的字符串,因此您还可以在一行中链接多个replaceAll调用。实际上,您在这里不需要replaceAll()。当您要替换与正则表达式模式匹配的子字符串时,这是必需的。只需使用String#replace()方法:

weatherLocation = weatherLocation.replace("how","")
                                 .replace("weather", "")
                                 .replace("like", "");

关于java - 为什么replaceAll在此代码行中不起作用? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17296271/

10-11 16:34