Search code examples
javastringstringbuilder

StringIndexOutOfBounds Exception when trying to remove part of StringBuilder


I`m trying to remove a subdirectory from a StringBuilder

StringBuilder mkPath = new StringBuilder("/sdcard/Downloads/mp3/mysong.mp3");

String nameToRemove = "/"+new File(mkPath.toString()).getName();

mkPath.delete(mkPath.lastIndexOf("/"),nameToRemove.length());

But it keeps throwing StringIndexOutOfBounds exception. Is there a way to fix this?


Solution

  • You are getting StringIndexOutOfBoundsException because mkPath.lastIndexOf("/") is 21 and nameToRemove.length() is 11.

    Replace

    mkPath.delete(mkPath.lastIndexOf("/"),nameToRemove.length());
    

    with

    mkPath.delete(mkPath.lastIndexOf("/"), mkPath.lastIndexOf("/") + nameToRemove.length());
    

    because the end index must be greater than the start index.

    Check StringBuilder.#delete(int, int) for more details on it.