How to represent empty char in Java Character class

后端 未结 16 903
遥遥无期
遥遥无期 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:37

    In java there is nothing as empty character literal, in other words, '' has no meaning unlike "" which means a empty String literal

    The closest you can go about representing empty character literal is through zero length char[], something like:

    char[] cArr = {};         // cArr is a zero length array
    char[] cArr = new char[0] // this does the same
    

    If you refer to String class its default constructor creates a empty character sequence using new char[0]

    Also, using Character.MIN_VALUE is not correct because it is not really empty character rather smallest value of type character.

    I also don't like Character c = null; as a solution mainly because jvm will throw NPE if it tries to un-box it. Secondly, null is basically a reference to nothing w.r.t reference type and here we are dealing with primitive type which don't accept null as a possible value.

    Assuming that in the string, say str, OP wants to replace all occurrences of a character, say 'x', with empty character '', then try using:

    str.replace("x", "");
    

提交回复
热议问题