Chip
Chip

Reputation: 155

Java String Remove one letter at a time

I'm trying to remove one letter at a time from a word. For example, if the word it math, I want to try: ath, mth, mah Right now I have:

  for (int i = 1; i < word.length() ; i++){
         String removed = word.substring(0, i -1) 
             + word.substring(i -1 , word.length());

  //do something with the word
}

This doesn't work because I get the error: java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Thanks for your help!

Upvotes: 1

Views: 678

Answers (4)

Abdalla Soliman
Abdalla Soliman

Reputation: 16

int wordLength = word.length();
for (int i = 0; i < wordLength; i++) {
    String removed = word.substring(0, i )
            + word.substring(i + 1, wordLength);
    System.out.println(removed);
    //do something with the word
}

You need to remove 1 char every time so u should make it like two words and concatenate each to other.

  1. The first word starts with no char (0 to 0) and the second word (1 to word length). So now you skip first char.
  2. You make the first word (0 to 1) and the second word (2 to word length). So now you skip second char etc.

Upvotes: 0

Evgeny Kochergin
Evgeny Kochergin

Reputation: 41

Following should work:

for (int i = 0; i < word.length(); i++) {
   String removed = word.substring(0, i) + word.substring(i + 1);
}

Upvotes: 1

Shawn Eion Smith
Shawn Eion Smith

Reputation: 457

Something like this should work.

public class LetterRemover {
  public static void main(String [] args) {
    String hello = "hello";

    for (int i = 1; i < hello.length(); ++i) {
      if(i == 1) {
        System.out.println(hello.substring(i));
      } else {
        System.out.println(hello.substring(0, i-1) + hello.substring(i));
      }
    }
  }
}

Upvotes: 0

muasif80
muasif80

Reputation: 6016

for (int i = 1; i < word.length() ; i++){
            String removed = word.substring(0, i - 1) 
                + word.substring(i , word.length());

            System.out.println(removed);
         //do something with the word
        }

Actually you need to start from i not i - 1 in getting the 2nd part of the final word. For example you can see this is needed and working word.substring(i , word.length());

It is not throwing the exception though.

Upvotes: 0

Related Questions