字符串替换方法不替换字符 [英] String replace method is not replacing characters
问题描述
我有一个以字符串形式传递的句子,我正在对单词"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", " ");
}
这里有我想念的东西吗?
Is there something I am missing here.
推荐答案
当我调试它时,逻辑确实落入了句子.替换.
And when I debug this the logic does fall into the sentence.replace.
是,然后您放弃返回值.
Yes, and then you discard the return value.
字符串是不可变的-调用replace
时,它不会更改 existing 字符串的内容-它会返回经过修改的 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", " ");
这适用于 all 字符串中的方法(substring
,toLowerCase
等).它们中的 None 都不会更改字符串的内容.
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
请注意,您实际上并不需要在某种情况下执行此操作-毕竟,如果句子不包含"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屋!