SoFunction
Updated on 2025-04-13

Solve: String index out of range: -1 error problem

: String index out of range: -1

String intercepts and subscripts cross bounds

: String index out of range: -1
    at (:1967)

Error code

("value", ().substring(0,().length()-1));

Modified code

if ((()) && ().length() >0){
                            ("value", ().substring(0,().length()-1));
                        }

Experience:

  • The source code of StringIndexOutOfBoundsException is as follows:
/**
 * Thrown by {@code String} methods to indicate that an index
 * is either negative or greater than the size of the string.  For
 * some methods such as the charAt method, this exception also is
 * thrown when the index is equal to the size of the string.
 */
public
class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
    private static final long serialVersionUID = -6762910422159637258L;
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with no
     * detail message.
     *
     * @since   JDK1.0.
     */
    public StringIndexOutOfBoundsException() {
        super();
    }
 
    /**
     * Constructs a {@code StringIndexOutOfBoundsException} with
     * the specified detail message.
     *
     * @param   s   the detail message.
     */
    public StringIndexOutOfBoundsException(String s) {
        super(s);
    }
 
    /**
     * Constructs a new {@code StringIndexOutOfBoundsException}
     * class with an argument indicating the illegal index.
     *
     * @param   index   the illegal index.
     */
    public StringIndexOutOfBoundsException(int index) {
        super("String index out of range: " + index);
    }
}

There are a total of the following methods that throw the exception:

()

()

()

()

()

()

()

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.