How to represent empty char in Java Character class

后端 未结 16 779
遥遥无期
遥遥无期 2020-11-29 02:11

I want to represent an empty character in Java as \"\" in String...

Like that char ch = an empty character;

Actually I want to rep

相关标签:
16条回答
  • 2020-11-29 02:41

    char means exactly one character. You can't assign zero characters to this type.

    That means that there is no char value for which String.replace(char, char) would return a string with a diffrent length.

    0 讨论(0)
  • 2020-11-29 02:41
    char ch = Character.MIN_VALUE;
    

    The code above will initialize the variable ch with the minimum value that a char can have (i.e. \u0000).

    0 讨论(0)
  • 2020-11-29 02:47

    As chars can be represented as Integers (ASCII-Codes), you can simply write:

    char c = 0;
    

    The 0 in ASCII-Code is null.

    0 讨论(0)
  • 2020-11-29 02:47

    You can only re-use an existing character. e.g. \0 If you put this in a String, you will have a String with one character in it.


    Say you want a char such that when you do

    String s = 
    char ch = ?
    String s2 = s + ch; // there is not char which does this.
    assert s.equals(s2);
    

    what you have to do instead is

    String s = 
    char ch = MY_NULL_CHAR;
    String s2 = ch == MY_NULL_CHAR ? s : s + ch;
    assert s.equals(s2);
    
    0 讨论(0)
  • 2020-11-29 02:48

    As Character is a class deriving from Object, you can assign null as "instance":

    Character myChar = null;
    

    Problem solved ;)

    0 讨论(0)
  • 2020-11-29 02:49

    this is how I do it.

    char[] myEmptyCharArray = "".toCharArray();
    
    0 讨论(0)
提交回复
热议问题