[英]Finding pattern in string using indexof
Can someone tell me why this is an infinte loop? 有人可以告诉我为什么这是无限循环吗?
private void splitBody() {
bodyparts=new Vector();
String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";
int previousIndex=0;
while(body.indexOf("<br />",previousIndex)!=-1) {
int index=body.indexOf("<br />",previousIndex);
System.out.println(body.substring(previousIndex, index));
bodyparts.addElement(body.substring(previousIndex, index));
previousIndex=index;
}
}
将最后一行更改为:
previousIndex = index + 1;
Because you don't change your body
string, so indexOf
always returns an index different that -1
since the substring is contained in body
. 因为您不更改body
字符串,所以indexOf
始终返回与-1
不同的索引,因为子字符串包含在body
。
Add body = body.substring(index);
添加body = body.substring(index);
at the end of the loop to fix that. 在循环结束时进行修复。
This should fix the issue: 这应该可以解决问题:
previousIndex=index + 1;
Otherwise you'll always find the first occurance of the pattern. 否则,您将始终找到该模式的首次出现。
Or - simplify the whole thing: 或者-简化整个过程:
String[] parts = body.split("<br />");
The indexOf operation return the starting position. indexOf操作返回起始位置。 If you want to move forward, increment the previousIndex like this. 如果要向前移动,请像这样增加前一个索引。
bodyparts=new Vector();
String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";
int previousIndex=0;
while(body.indexOf("<br />",previousIndex)!=-1) {
int index=body.indexOf("<br />",previousIndex);
System.out.println(body.substring(previousIndex, index));
bodyparts.addElement(body.substring(previousIndex, index));
previousIndex=index+("<br />".size());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.