I want to represent an empty character in Java as \"\"
in String...
Like that char ch = an empty character;
Actually I want to rep
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
Hey i always make methods for custom stuff that is usually not implemented in java. Here is a simple method i made for removing character from String Fast
public static String removeChar(String str, char c){
StringBuilder strNew=new StringBuilder(str.length());
char charRead;
for(int i=0;i<str.length();i++){
charRead=str.charAt(i);
if(charRead!=c)
strNew.append(charRead);
}
return strNew.toString();
}
For explaintion, yes there is no null character for replacing, but you can remove character like this. I know its a old question, but i am posting this answer because this code may be helpful for some persons.
You may assign '\u0000'
(or 0).
For this purpose, use Character.MIN_VALUE.
Character ch = Character.MIN_VALUE;
You can do something like this:
mystring.replace(""+ch, "");
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", "");
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"