如何使用.substring方法从索引开始并在其后获取x个数字或字符? [英] How to use .substring method to start at an index and grab x number or characters after it?

查看:43
本文介绍了如何使用.substring方法从索引开始并在其后获取x个数字或字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 have to give it a start location and a end location but the end location needs to be a location on the original string after the start.

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

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

This is an example of how I would like the code to work, it would make a substring starting at test and stop after 7 characters returning "test string". However if I use this code I get a indexOutOfBounds exception because 6 is before test. Working code would be the following

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

哪个将返回测试字符串".但是我不知道最后一个数字是什么,因为html总是在变化.因此,问题是我必须做什么,以便我可以开始一个特定的位置并在其后结束x个字符.任何帮助将非常感激!谢谢!

Which would return "test string". But I don't know what the last number is going to be since the html is always changing. SO THE QUESTION IS what do I have to do so that I can start a specific location and end a x amount of characters after it? Any help would be much appreciated! Thanks!

推荐答案

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

Since the second parameter is an index, not the length, you need to store the initial position, and add the length to it, like this:

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

演示.

这篇关于如何使用.substring方法从索引开始并在其后获取x个数字或字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆