1

例如,分配是a从字符串“ I am Sam am I Sam”中删除 char '',这是我到目前为止的一些代码:

public String removeLetters() {
    String cleaned=sentence;
    StringBuilder builder = new StringBuilder(cleaned);

    while(cleaned.indexOf(lookFor) != -1) {
        builder.deleteCharAt(cleaned.indexOf(lookFor));
    }
    return builder.toString();
}

当没有 while 循环时,此方法返回正常(尽管它只删除一个字符),但是当我使用 while 循环运行它时,我得到了OutOfBounds错误。

4

5 回答 5

1

改变这个:

while(cleaned.indexOf(lookFor) != -1) {
    builder.deleteCharAt(cleaned.indexOf(lookFor));
}

有了这个:

while(builder.indexOf(Character.toString(lookFor)) != -1) {
    builder.deleteCharAt(builder.indexOf(Character.toString(lookFor)));
}
于 2013-10-24T16:25:01.797 回答
1

您可以使用以下方法直接执行此操作String#replace

String cleaned = "I am Sam am I Sam";
cleaned = cleaned.replace("a", "");
System.out.println(cleaned);   // I m Sm m I Sm
于 2013-10-24T16:25:16.433 回答
0

必须从构建器中删除,而不是源字符串。此外,您最初有一个无限循环,试图修改构建器字符串,但只检查源字符串,这不会改变。这编译并运行良好:

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();
}
于 2013-10-24T16:34:32.723 回答
0

while循环中的条件是 中的索引cleaned StringBuilder,但是您使用相同的索引从中删除字符builder- 删除第一个字符后,它们不再匹配。

简而言之:

public String removeLetters() {
    String cleaned=sentence;
    StringBuilder builder = new StringBuilder(cleaned);

    while(builder.indexOf(lookFor) != -1) {
        builder.deleteCharAt(builder.indexOf(lookFor));
    }

    return builder.toString();
}
于 2013-10-24T16:25:56.683 回答
0

试试这个。

cleaned.replaceAll(lookFor,"");
于 2013-10-24T16:27:36.250 回答