172

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

Like that char ch = an empty character;

Actually I want to replace a character without leaving space.

I think it might be sufficient to understand what this means: no character not even space.

3
  • 2
    Show an example of the replace operation you want to perform. Commented Dec 16, 2011 at 12:53
  • 1
    @rahulsri I can't see the code you are referring to. Commented Dec 16, 2011 at 13:09
  • 5
    I think that OP wants to perform String.replace(' ', EMPTY_CHARACTER) to have the same effect as String.replace(" ", ""). I.e. remove all spaces. Commented Mar 13, 2017 at 7:45

18 Answers 18

181

You may assign '\u0000' (or 0). For this purpose, use Character.MIN_VALUE.

Character ch = Character.MIN_VALUE;
Sign up to request clarification or add additional context in comments.

8 Comments

What does '\0' exactly mean? @AVD
@cinnamontoast - Its a null char literal
A null char literal is still a character and takes space in storage.
The question asks for a way to represent 'no characters'. While the null character is useful in many situations, it is still a character in its own right, so cannot be the answer to this question. The correct answer, already given by user3001, is to use Java's boxed Character reference type and give it 'null' value when 'no character' is needed.
@AVD Yes, and rahulsri asks how to represent a missing character. So a null Character reference fits.
|
143

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.

Comments

45

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

Character myChar = null;

Problem solved ;)

7 Comments

Although this does not answer the OP, it's what I was looking for.
The MOST correct answer is "it cannot be done". This is the nearest you can get.
Character is, but char isn't.
LOL: I have Java throwing a null pointer exception when I assign null to Character
|
18

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

char c = 0;

The 0 in ASCII-Code is null.

3 Comments

0 as a UTF-16 code unit (char) is the complete UTF-16 encoding for the Unicode codepoint U+0000. Any similarity to some other character set or character encoding is irrelevant. UTF-16 is what Java uses.
@TomBlodget Could you please elaborate more? I don't understand whether you agree or disagree with the answer.
@Wit Java uses UTF-16, the integer doesn't represent a ASCII code. In case of UTF-16 surrogates a char might hold an integer value that could be a valid ASCII code without actually represending that same character
16

An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.

You say you want to "replace a character without leaving a space".

If you are dealing with a char[], then you would create a new char[] with that element removed.

If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.

Here are some samples of how you could remove a char:

public static void main(String[] args) throws Exception {

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}

1 Comment

Apart from replace() solution other two will replace just the first occurrence of the character and not all.
8

If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

Comments

5

I was looking for this. Simply set the char c = 0; and it works perfectly. Try it.

For example, if you are trying to remove duplicate characters from a String , one way would be to convert the string to char array and store in a hashset of characters which would automatically prevent duplicates.

Another way, however, will be to convert the string to a char array, use two for-loops and compare each character with the rest of the string/char array (a Big O on N^2 activity), then for each duplicate found just set that char to 0..

...and use new String(char[]) to convert the resulting char array to string and then sysout to print (this is all java btw). you will observe all chars set to zero are simply not there and all duplicates are gone. long post, but just wanted to give you an example.

so yes set char c = 0; or if for char array, set cArray[i]=0 for that specific duplicate character and you will have removed it.

Comments

4

You can't. "" is the literal for a string, which contains no characters. It does not contain the "empty character" (whatever you mean by that).

Comments

4

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", "");

Comments

2
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).

Comments

1

this is how I do it.

char[] myEmptyCharArray = "".toCharArray();

1 Comment

That's not an empty character. It is a zero length character array.
1

You can do something like this:

mystring.replace(""+ch, "");

Comments

1

String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE

Where EMPTY_SPACE = " " (this is String) TAB = '\t' (this is Character)

String after = before.replaceAll(" ", "").replace('\t', '\0') means after = "word"

Comments

0

Use the \b operator (the backspace escape operator) in the second parameter

String test= "Anna Banana";

System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string

1 Comment

xD ... amusing things will result if trying to use thus mangled (yes, mangled, mauled, disfigured) string as part of e.g. file name.
0

In Kotlin, using below code solved my problem.

Char.MIN_VALUE

Comments

0

The highest voted answer does NOT represent an empty char, it is still a character, to be more precise a CONTROL character which can be represented by:

Character ascii = 0; // ASCII
Character unicode = '\u0000'; //UTF-16, which is also what Java use
Character min = Character.MIN_VALUE;

The Null character (The important bits)

The null character (also null terminator) is a control character with the value zero.[1][2][3][4] It is present in many character sets, including those defined by the Baudot and ITA2 codes, ISO/IEC 646 (or ASCII), the C0 control code, the Universal Coded Character Set (or Unicode), and EBCDIC. It is available in nearly all mainstream programming languages.[5] It is often abbreviated as NUL (or NULL, though in some contexts that term is used for the null pointer). In 8-bit codes, it is known as a null byte.

Today the character has much more significance in the programming language C and its derivatives and in many data formats, where it serves as a reserved character used to signify the end of a string,[6] often called a null-terminated string.[7] This allows the string to be any length with only the overhead of one byte;

char

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Character

The Character class wraps a value of the primitive type char in an object. An object of class Character contains a single field whose type is char. In addition, this class provides a large number of static methods for determining a character's category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.

In a nutshell, in Java, there is no empty character literal.

Comments

0
 Character newChar = null;

As we using here wrapper class to declare newChar variable as empty.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

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);

3 Comments

What do you mean it not worked? DO you mean it doesn't compile? In that case it would be char ch = '\0'; or char ch = 0;
@rahulsri All characters are characters and there is no character which is not a character. You need to work out what your real requirement is and try to solve it a different way. The nul character is one of the many special characters which indicates its a character which is not really there, but it is itself still a character.
"If god can do anything, can god create a rock even he cannot lift?" Its similar to the question; Can you create a character which is not a character?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.