如何使用.substring方法从索引开始并在其后获取x个数字或字符?

所以我正在解析html,我正在尝试从某个位置开始创建一个子串,然后停止941个字符。 Java中的.substring方法的工作方式是你必须给它一个起始位置和一个结束位置,但结束位置需要在开始后是原始字符串上的一个位置。

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

这是我希望代码如何工作的一个例子,它会使一个子字符串从test开始,并在7个字符返回“test string”后停止。 但是,如果我使用此代码,我会得到一个indexOutOfBoundsexception,因为6是在测试之前。 工作代码如下

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

哪个会返回“测试字符串”。 但我不知道最后一个数字是什么,因为html总是在变化。 所以问题是我必须做些什么才能开始一个特定的位置并在它之后结束数量的字符? 任何帮助将非常感激! 谢谢!

由于第二个参数是索引而不是长度,因此您需要存储初始位置,并为其添加长度,如下所示:

 String html = "This is a test string for example"; int pos = html.indexOf("test"); String res = html.substring(pos, pos+11); 

演示。

请参阅String.substring源代码。

 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); } 

在此源(第8~9行)中,第二个参数大于第一个参数。

你需要编辑它。

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

希望,这将解决问题。