String replace method is not replacing characters

后端 未结 5 1101
小鲜肉
小鲜肉 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 07:57

    You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

    sentence = sentence.replace("and", " ");
    

    A String is immutable in java. Methods like replace return a new String.

    Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

提交回复
热议问题