欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

String中subString(int start,int end) index的问题,stringsubstring

来源: javaer 分享于  点击 45192 次 点评:11

String中subString(int start,int end) index的问题,stringsubstring


这个问题每次遇到很烦的时候就说明,问题虽然小,但是确实没理解明白,试来试去,还是源码解决最靠谱。

/**
     * Returns a string containing the given subsequence of this string.
     * The returned string shares this string's <a href="#backing_array">backing array</a>.
     *
     * @param start the start offset. 下标index从start开始
     * @param end the end+1 offset. the end目标下标,end = the end+1
     * 
     * 例如:
     * Hello World 转char[]={'H','e','l','l','o',' ','W','o','r','l','d'}
     * char[0]='H',char[4]='o'
     * 从Hello World,截取Hello,start=0,the end =4,end =5.
     * 
     * @throws IndexOutOfBoundsException
     *             if {@code start < 0}, {@code start > end} or {@code end > length()}.
     */
    public String substring(int start, int end) {
        if (start == 0 && end == count) {
            return this;
        }
        // Fast range check.
        if (start >= 0 && start <= end && end <= count) {
             //start是截取源字符串的开始下标,往后截取长度为end-start
             //如果start为0,截取长度为5的字符串,end为5
            return fastSubstring(start, end - start);
        }
        throw startEndAndLength(start, end);
    }
    /**
     * 从start截取length长度的字符串
     */
    private native String fastSubstring(int start, int length);

相关文章

    暂无相关文章

用户点评