Finding pattern in string using indexof
Can someone tell me why this is an infinte loop?
private void splitBody() {
bodyparts=new Vector();
String body = "<开发者_StackOverflow社区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;
}
}
Change the last line to:
previousIndex = index + 1;
The indexOf operation return the starting position. 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());
}
Because you don't change your body
string, so indexOf
always returns an index different that -1
since the substring is contained in body
.
Add 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 />");
精彩评论