1

Possible Duplicate:
How to represent empty char in Java Character class

I am using the replace function as defined in java.lang.String, and I tried using "\0" as the equivalent for "" (blank String) but it adds a space not a blank string.

Is there a Character equivalent for a blank String?

Community
  • 1
  • 1
hologram
  • 533
  • 2
  • 5
  • 21

5 Answers5

6

There is no such thing as an "empty character". A char is a value-type, so it has to have a value. An absence of a value is the absence of a char - which is why you can have empty strings (i.e. "no characters") and a nullable char, but not an "empty char".

Anyway, the String.replace(char, char) method is meant to substitute one character for another. This operation is very simple because it means that a single block of known size has to be allocated. Whereas String.replaceAll(string,string) is a considerably more complicated method to implement, which is why they're different.

Unfortunately there is no String.replace(char,string) method - but I hope you can understand why.

Dai
  • 141,631
  • 28
  • 261
  • 374
1

There are infinitely many blank Strings in a given String... how many "nothings" are between 'a' and 'b' in "ab"? It's like dividing by zero!

durron597
  • 31,968
  • 17
  • 99
  • 158
1

I supose you want to replace "something" with "", you can't do it the other way around...

       String ou="test";
       ou = ou.replace("t", "");
       System.out.println(ou);

the output will be: es

with the char version of replace this will not work as '' is not a valid char.

Frank
  • 16,476
  • 7
  • 38
  • 51
1

You can't use String.replace(char,char) if you want to remove characters. There is no empty character. That method will never change the length of the string, it just replaces a character with another character

You have to use String.replaceAll(java.lang.String, java.lang.String) (or replaceFirst)

"ababababa".replaceAll("a", ""); // returns "bbbb"
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

There isn't, but notice that there is a String.replace(CharSequence, CharSequence), so you should be able to call String.replace with a string as the first argument and "" as the second argument.

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
osandov
  • 121
  • 1
  • 4