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
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.