Sourav Mehra
Sourav Mehra

Reputation: 445

Blank character constant in Java

How can we replace a particular char constant with blank in Java?

\0 replaces with space char and not with blank.

Input :

    String amount = "1.22.33,11";

Desired result : 12233,11

Upvotes: 2

Views: 1789

Answers (2)

Anonymous
Anonymous

Reputation: 86379

    String amount = "1.22.33,11";
    String result = amount.replace(".", "");
    System.out.println(result);

Output:

12233,11

No need to use a regular expression nor an external dependency.

The replace​(CharSequence target, CharSequence replacement) method of the String class replaces every occurrence of the literal target string with the replacement string. So just give the empty string as replacement.

Your task may be described as removing occurrences of .. So replacing with a “blank” character, whatever that is, is not the right solution, you would still have some character there. Instead we replace a one-character string by another string that has no characters in it.

As @Lino pointed out in comments, JDK version up to at least 8 (I haven’t checked 9 nor 10) compile a regular expression into a Pattern for each invocation of the method. In Java 11 an efficient implementation has been provided.

Upvotes: 3

Lino
Lino

Reputation: 19910

You can use regex for this:

String result = amount.replaceAll("\\.", "");

\. matches every literal period (.) and replaces it with an empty string ("")


You can further optimize this if you save the regex as a java.util.regex.Pattern into a variable:

private static final Pattern DOT = Pattern.compile("\\.");

Which you then can use like this:

String result = DOT.matcher(amount).replaceAll("");

Upvotes: 3

Related Questions