-3

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Beatrice
  • 3
  • 1
  • 3
  • 1
    https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String) – glennsl Sep 27 '17 at 02:18

2 Answers2

2

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 ("$", "");  
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

replaceAll is expecting two strings, but you are passing chars. Use " instead of '

JDollars
  • 61
  • 4