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
  • 521
  • 2
  • 5
  • 20

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
  • 126,861
  • 25
  • 221
  • 322
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,426
  • 16
  • 97
  • 154
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,029
  • 6
  • 36
  • 49
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"
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
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
  • 24,095
  • 8
  • 74
  • 100
osandov
  • 101
  • 1
  • 4