Egek92 Egek92 - 11 days ago 5
Java Question

How to remove a character in a String in Java?

I was solving some beginner Java examples and there is a question for which I have to return a new string where the character at index

n
has been removed.

For example:

missingChar("kitten", 1) → "ktten"


I have to remove the first char in the String.

I tried this but it didn't work:

for (int i=0;i<str.length()-1;i++){
while (i==n){
str=str.replaceFirst(String.valueOf(str.charAt(i)),"");
return str;
}
}


Can someone tell me what is wrong with my code?

Answer

Here is a simple way to do what you want:

   String missingChar(String s, int i) {
        return s.substring(0, i) + s.substring(i+1);
    }

The code you provided in your question replaces the first occurrence of the character in the whole string. And, btw, an if would have the same effect as the while because of the return statement. The for loop is also useless because you have the index of the character (I guess it's n?)