For example myString = "Java is Cool";
this should return "JavaisCool"..
the replace method of the String class cant seem to work,
i did :
'\u0020' is a space
'\u0000' is null
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(" ", "");
Alan Moore wrote:The method replace(CharSequence, CharSequence) was added in JDK 1.5; that's what Sanjaya is talking about. Before that, there was only the one "replace" method, which (as you've seen) doesn't do what you want. If you're running JDK1.4.x, you can use replaceAll(" ", "") instead. Also, remember that strings are immutable, so you have to take the return value of whichever method you use:
can i use the same method for replacing all $ with '''' . like replaceAll("$",'''') . if not then how can we replace a $ sign with space in java1.4 ?
Replacing a $ with empty Strings is a bit harder, because $ has special meaning in regular expressions (which is what replaceAll takes). You need to escape that in one of two ways:
1) str.replace("\\$", ""). To escape any regular expression meta character, you need to add two backslashes in front of it - one to escape the meta character, and one to escape the \ so you can use it inside Strings.
2) str.replace("\\Q$\\E", ""). Anything between \Q and \E is treated as literal values in regular expression. There is method Pattern.quote to make this easier, but unfortunately that method is available since Java 5.0...
Speaking of Java 1.4 - why are you still using that fossil? It's been EOL (end of life) for several years already.