Search code examples
javastringbuffer

delete a substring from a string buffer using Java


I want to remove a substring from a string buffer every time this substring occures, what I did so far is:

  public static void main(String[] args) {

        String text = "Alice Bob Alice Bob Alice Bob";
        String substr = "Alice";            
        StringBuffer strbuf = new StringBuffer(text);
        strbuf.indexOf(substr);
        strbuf.lastIndexOf(substr);
        while (strbuf != null) {
                strbuf.delete(strbuf.indexOf(substr), strbuf.indexOf(substr) + substr.length());
                System.out.println(strbuf.toString());
            }
}

I want to remove every occurrence of "Alice". But it gives the following error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

I think that the error in the while line. Any ideas?


Solution

  • your problem is you are trying to delete a substring that isn't there (after you've removed all the instances of it). You have to change you loop bounds to something like

    while(strbuf != null && strbuf.indexOf(substr) != -1)