字符串替换方法不替换字符 [英] String replace method is not replacing characters
问题描述
我有一个作为字符串传入的句子,我正在替换单词and",我想用"替换它.它并没有用空格代替and"这个词.下面是我的逻辑示例.当我调试它时,逻辑确实属于句子.替换.
I have a sentence that is passed in as a string and I am doing a replace on the word "and" and I want to replace it with " ". And it's not replacing the word "and" with white space. Below is an example of my logic. And when I debug this the logic does fall into the sentence.replace.
String sentence = "Define, Measure, Analyze, Design and Verify"
if (sentence.contains("and")){
sentence.replace("and", " ");
}
我在这里遗漏了什么.
推荐答案
当我调试这个时,逻辑确实落入了sentence.replace.
And when I debug this the logic does fall into the sentence.replace.
是的,然后您丢弃返回值.
Yes, and then you discard the return value.
Java 中的字符串是不可变的——当你调用 replace
时,它不会改变 现有 字符串的内容——它返回一个 new 修改后的字符串.所以你想要:
Strings in Java are immutable - when you call replace
, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
这适用于所有 String 中的方法(substring
、toLowerCase
等).没有改变字符串的内容.
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
请注意,您实际上并不需要在条件中执行此操作 - 毕竟,如果句子 doesn't 包含 "and"
,则没有任何危害执行替换:
Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and"
, it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");
这篇关于字符串替换方法不替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!