hhh*_*hhh 127 java string match
String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
Run Code Online (Sandbox Code Playgroud)
pol*_*nts 249
执行此操作的方法系列包括:
返回指定子字符串[ 从指定索引开始向前搜索(或向后)] 的第一个(或最后一个)出现的字符串中的索引.
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
Run Code Online (Sandbox Code Playgroud)
小智 39
这适用于正则表达式.
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
Run Code Online (Sandbox Code Playgroud)
输出:
在指数2 - 5找到'爱'
一般规则 :
正如其他人所说,text.indexOf(match)
用来寻找单一的比赛.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Run Code Online (Sandbox Code Playgroud)
由于@ StephenC关于代码可维护性的评论以及我自己在理解@polygenelubricants的答案时遇到的困难,我想找到另一种方法来获取文本字符串中匹配的所有索引.以下代码(从此答案修改)执行此操作:
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);
}
Run Code Online (Sandbox Code Playgroud)