Search code examples
javastringcharacterreplaceall

Error while using the replaceAll() method


I have some code that looks like this:

str.replaceAll('$', ' ');
return str;

What I'm trying to do here is replace every instance of $ in my string str with a space. But I get this error when I compile:

incompatible types: char cannot be converted to String
        str.replaceAll('$', ' ');
                       ^

But I'm not converting anything to string, I'm replacing a character by a space character. So why am I getting that error?


Solution

  • As per the javadocs the method you want to use is

    public String replaceAll(String regex,
                    String replacement)
    

    so your code should look like

    str.replaceAll ("$", "");  
    

    note

    If you really need to use replaceAll then escape the "$" mark \\$

    BUT

    As in regex "$" has a special meaning (end of the String) and you do not have any special regex requirements then use replace instead

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