String replace method is not replacing characters

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

    Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

    public class Test{
    
        public static void main(String[] args) {
    
            String sentence = "Define, Measure, Analyze, Design and Verify";
    
            String replaced = sentence.replace("and", "");
            System.out.println(replaced);
    
        }
    }
    

    As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

提交回复
热议问题