36

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?

0

2 Answers 2

40

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I get an error saying that The method replace(char, char) in the type String is not applicable for the arguments (char, String)
@capcom You want string.replace(".", "")
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.
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 Ya, I have that too. That's not the problem, so I left that out for simplicity.
30

try :

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

Other way is to use replaceAll :

string.replaceAll("\\.","");

1 Comment

A downside of using replaceAll is the it will be processed as regex, so always prefer replace over replaceAll when possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.