当前位置: 代码网 > it编程>编程语言>Java > 解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题

解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题

2025年03月22日 Java 我要评论
java.lang.stringindexoutofboundsexception: string index out of range: -1字符串截取下标越界java.lang.stringind

java.lang.stringindexoutofboundsexception: string index out of range: -1

字符串截取下标越界

java.lang.stringindexoutofboundsexception: string index out of range: -1
    at java.lang.string.substring(string.java:1967)

出错代码

result.put("value", valuebuilder.tostring().substring(0,valuebuilder.tostring().length()-1));

修改后代码

if (stringutils.isnotblank(valuebuilder.tostring()) && valuebuilder.tostring().length() >0){
                            result.put("value", valuebuilder.tostring().substring(0,valuebuilder.tostring().length()-1));
                        }

心得:

  • stringindexoutofboundsexception 异常源码如下:
/**
 * 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);
    }
}

总共有以下几个方法会抛出该异常:

string.substring()

string.charat()

string.codepointat()

string.codepointbefore()

string.subsequence()

string.getchars()

string.getbytes()

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com