Egek92 Egek92 - 1 year ago 86
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

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){
return str;

Can someone tell me what is wrong with my code?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download