Reputation: 15
The assignment is to, for example, remove char 'a
' from the String "I am Sam am I Sam
", this is a bit code I have so far:
public String removeLetters() {
String cleaned=sentence;
StringBuilder builder = new StringBuilder(cleaned);
while(cleaned.indexOf(lookFor) != -1) {
builder.deleteCharAt(cleaned.indexOf(lookFor));
}
return builder.toString();
}
This method returns fine when there's no while loop (though it only removes one char), but when I run it with the while loop I get the OutOfBounds
error.
Upvotes: 1
Views: 1397
Reputation: 4500
Have to remove from the builder, not the source string. Also, you initially had an infinite loop, attempting to modify the builder string, but only checking the source string, which wouldn't change. This compiled and ran fine:
public String removeLetters()
{
String lookFor = "a";
String original="I am Sam am I Sam";
StringBuilder builder = new StringBuilder(original);
while(builder.indexOf(lookFor) != -1) {
builder.deleteCharAt(builder.indexOf(lookFor));
}
return builder.toString();
}
Upvotes: 0
Reputation: 310993
The condition in the while
loop is the index in the cleaned
StringBuilder
, but then you're using the same index to delete characters from builder
- after the first character has been deleted, they no longer match.
In short:
public String removeLetters() {
String cleaned=sentence;
StringBuilder builder = new StringBuilder(cleaned);
while(builder.indexOf(lookFor) != -1) {
builder.deleteCharAt(builder.indexOf(lookFor));
}
return builder.toString();
}
Upvotes: 0
Reputation: 213193
You can directly do this using String#replace
method:
String cleaned = "I am Sam am I Sam";
cleaned = cleaned.replace("a", "");
System.out.println(cleaned); // I m Sm m I Sm
Upvotes: 1
Reputation: 3223
Change this:
while(cleaned.indexOf(lookFor) != -1) {
builder.deleteCharAt(cleaned.indexOf(lookFor));
}
with this:
while(builder.indexOf(Character.toString(lookFor)) != -1) {
builder.deleteCharAt(builder.indexOf(Character.toString(lookFor)));
}
Upvotes: 1