String replace method is not replacing characters

后端 未结 5 1203
小鲜肉
小鲜肉 2020-11-21 07:39

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\" w

5条回答
  •  故里飘歌
    2020-11-21 08:11

    And when I debug this the logic does fall into the sentence.replace.

    Yes, and then you discard the return value.

    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", " ");
    

    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", " ");
    

提交回复
热议问题