Java:获取String中匹配位置的方法? [英] Java: method to get position of a match in a String?
本文介绍了Java:获取String中匹配位置的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
推荐答案
执行此操作的方法系列是:
The family of methods that does this are:
-
int indexOf(String str)
返回fir字符串中的索引st(或last )出现指定子字符串[从指定索引开始向前搜索(或向后)]。
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
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"
这篇关于Java:获取String中匹配位置的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文