How to use .substring method to start at an index and grab x number or characters after it?

前端 未结 2 377
轻奢々
轻奢々 2021-01-25 04:15

so I\'m parsing html and I\'m trying to create a substring starting at a certain location and stop 941 characters after that. The way the .substring method in Java works is you

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 04:38

    Please refer to the String.substring source.

    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }
    

    in this source (line 8~9), second parameter bigger than first parameter.

    you will need to edit this.

    String html = "This is a test string for example";
    html.substring(html.indexOf("test"), (6+html.indexOf("test")));
    

    hopefully, that will solve the problem.

提交回复
热议问题