Finding second occurrence of a substring in a string in Java
我们给了一个字符串
当字符串
在这种情况下,
使用
1 | str.indexOf("is", str.indexOf("is") + 1); |
我在用:
Apache Commons Lang:StringUtils.ordinalIndexOf()
1 | StringUtils.ordinalIndexOf("Java Language","a", 2) |
1 2 | int first = string.indexOf("is"); int second = string.indexOf("is", first + 1); |
此重载开始从给定索引中查找子字符串。
您可以编写一个函数以返回出现位置的数组,Java具有String.regionMatches函数,这非常方便
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static ArrayList<Integer> occurrencesPos(String str, String substr) { final boolean ignoreCase = true; int substrLength = substr.length(); int strLength = str.length(); ArrayList<Integer> occurrenceArr = new ArrayList<Integer>(); for(int i = 0; i < strLength - substrLength + 1; i++) { if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) { occurrenceArr.add(i); } } return occurrenceArr; } |
我认为可以使用循环。
1 2 3 | 1 - check if the last index of substring is not the end of the main string. 2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string 3 - repeat the steps in a loop |