Java: method to get position of a match in a Strin

2019-01-03 14:24发布

String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?

13条回答
甜甜的少女心
2楼-- · 2019-01-03 15:30

Finding a single index

As others have said, use text.indexOf(match) to find a single match.

String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10

Finding multiple indexes

Because of @StephenC's comment about code maintainability and my own difficulty in understanding @polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:

String text = "0123hello9012hello8901hello7890";
String match = "hello";

int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) {  // indexOf returns -1 if no match found
    System.out.println(index);
    index = text.indexOf(match, index + matchLength);
}
查看更多
登录 后发表回答