-2

In java i tried replace char with ''. But it's showing "Empty Literal Character" error.I have condition about certain characters must be '' , not ' ' Not include empty one character. Here is example code:

for(int i=0; int<name.length;i++){
    name=name.replace(name.charAt(i),'');
    }

How can i do this ? Can you help ?

  • 1
    You can't replace a character with nothing. You have to actually remove the character from the string. – Federico klez Culloca May 01 '20 at 09:51
  • What's the point here? You have `int` which you probably want to be `i` and then, your going through each character and replacing it with nothing? The string solutions would change the length and your loop would be a bit junk. – matt May 01 '20 at 10:12
  • After specific index in my string, thats characters must be ''. I asked like this for easy understanding. There was char empty error and duplicated question is including specific value. Mine is depending user value – Serdar YILMAZ May 01 '20 at 10:21
  • Strings are immutable. That means you really aren't deleting a character, you're merely creating a new String that is a copy of the old string with the one character deleted. – NomadMaker May 01 '20 at 11:19
  • @SerdarYILMAZ after a specific index you want the string to be blank? You should check out [String.subString](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring\(int,int\)) you can call it once and you don't have to make a loop. – matt May 01 '20 at 12:21

2 Answers2

2

You can't have a character representing nothing. You need a character sequence of length zero, i.e. an empty string.

As such, your first argument also needs to be converted to use the String, String signature.

name = name.replace(Character.toString(name.charAt(i)), "");
Michael
  • 41,989
  • 11
  • 82
  • 128
0

If you want to remove some specific characters, then you can try it this way:

//Convert String to CharArray
   char[] ch = name.toCharArray();
   String newName = "";
   for (char c: ch) {
    if (wantThisCharacter(c)) newName+=c;
}
    name = newName;
jsgrewal12
  • 128
  • 9