Another remark with regard to your original idea: Replacing a character by a null character does not remove the original character from the string. It just replaces the character with another character with code 0.
And I'll repeat what Fred and
Alan said, because it's a very important notion: String is immutable, which means that you cannot modify a String after creating it. Class String does not contain any methods that modify the String object itself. Instead, the methods of class String return a new String object. So replace(...) does not change the String itself, it returns a new String object that contains the modified value. So you must write this:
// Note! Assign the return value of replaceAll to the variable str
str = str.replaceAll(" ", "");
Just doing this will not work:
// Doesn't work because String is immutable
str.replaceAll(" ", "");