String replace method is not replacing characters

后端 未结 5 1087
小鲜肉
小鲜肉 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:56

    You should re-assign the result of the replacement, like this:

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

    Be aware that the String class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String must be assigned to a variable or used immediately for the change to take effect.

提交回复
热议问题