字符串不替换字符 [英] String not replacing characters

查看:132
本文介绍了字符串不替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以字符串形式传入的句子,我正在对和这个词进行替换,我想用替换它。而且它并没有用空格替换和这个词。以下是我的逻辑示例。当我调试它时,逻辑确实属于sentence.replace。

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中的字符串是不可变的 - 当你调用替换,它不会更改现有字符串的内容 - 它会返回带有修改的 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", " ");

这适用于所有字符串中的方法( substring toLowerCase 等)。 它们会改变字符串的内容。

This applies to all the methods in String (substring, toLowerCase etc). None of them change the contents of the string.

请注意,您并不需要在某种情况下执行此操作 - 毕竟,如果句子包含,那么执行替换是没有害处的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆