Reputation: 155
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
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.
Upvotes: 0
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
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
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