Remove all occurrences of char from string

evilReiko picture evilReiko · Jan 2, 2011 · Viewed 723.4k times · Source

I can use this:

String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''

Is there a way to remove all occurrences of character X from a String in Java?

I tried this and is not what I want: str.replace('X',' '); //replace with space

Answer

LukeH picture LukeH · Jan 2, 2011

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");