繁体   English   中英

我正在尝试将字符串中的模式“我们的”替换为“或”但是这不起作用

[英]I am trying to replace the pattern "our" in the string to become "or" however this is not working

String str1 = "谣言是邻居们表现出良好的行为,因为他受到宠爱而努力帮助迈克。";

str1.replaceAll("我们的", "或");

System.out.println(str1);

方法replaceAll返回一个新字符串,其中匹配的 substring 的每个匹配项都将替换为替换字符串。

您的代码不起作用,因为String是不可变的。 所以, str1.replaceAll("our", "or"); 不会改变str1

试试这个代码:

    String str1 = "I am trying to replace the pattern.";
    String str2 = str1.replaceAll("replace", "change");
    System.out.println(str2);

如果您不知道str2 ,请尝试以下代码:

    String str1 = "I am trying to replace the pattern.";
    System.out.println(str1.replaceAll("replace", "change"));

并阅读Java 中的字符串不变性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM