34

Suppose I have the following in String format:

2.2

And I want to replace the decimal point with an empty space, to make it look like this:

22

How do I do this? I thought replace would have done the trick, but when I try it like this:

string.replace('.', '');

I get an error with the '' because it supposedly isn't a character. That makes sense, so how else can I accomplish what I want?

capcom
  • 3,257
  • 12
  • 40
  • 50

2 Answers2

38

If you just exchange single for double quotes, this will work because an empty string is a legal value, as opposed to an "empty character", and there's an overload replace(CharSequence, CharSequence). Keep in mind that CharSequence is the supertype of String.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • 3
    I get an error saying that `The method replace(char, char) in the type String is not applicable for the arguments (char, String)` – capcom Nov 03 '12 at 14:04
  • 3
    @capcom You want `string.replace(".", "")` – arshajii Nov 03 '12 at 14:04
  • Oh I tried that, but I get an error during run time. I should have mentioned that this is for Android. So my app is force closed if I use double quotes in `replace`. – capcom Nov 03 '12 at 14:05
  • 1
    Strings are immutable, so `replace()` won't change the string, it will return a new one. You will have to write `yourString = yourString.replace(".", "");` – jlordo Nov 03 '12 at 14:07
  • @jlordo Ya, I have that too. That's not the problem, so I left that out for simplicity. – capcom Nov 03 '12 at 14:08
31

try :

string.replace(".", "");

Other way is to use replaceAll :

string.replaceAll("\\.","");
Grisha Weintraub
  • 7,803
  • 1
  • 25
  • 45
  • 1
    A downside of using replaceAll is the it will be processed as regex, so always prefer replace over replaceAll when possible. – MYK Dec 29 '21 at 10:37