0

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85
  • 3
    "But it didn't work". What did not work? Where are you stuck? Are you getting an exception? – QBrute Nov 28 '16 at 13:57
  • 1
    The method you are looking for is [substring()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)). – Florent Bayle Nov 28 '16 at 13:57

1 Answers1

6

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

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • Yeah I guess loops are unnecessary `String a = str.substring(0, n); String b = str.substring(n+1, str.length()); return a+b` worked, thanks! – Ege Kuzubasioglu Nov 28 '16 at 14:19