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
I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:
Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
int numOfOcurrences = 2;
for(int i = 0; i < numOfOcurrences; i++) matcher.find();
System.out.println("Index: " + matcher.start());
public static int nthIndexOf(String str, String subStr, int count) {
int ind = -1;
while(count > 0) {
ind = str.indexOf(subStr, ind + 1);
if(ind == -1) return -1;
count--;
}
return ind;
}
public class NthOccuranceExample {
public static void main(String[] args) {
String str1 = "helloworld good morning good evening good night";
String str2 = "ing";
int n = 2;
int index = nthOccurrence(str1, str2, n);
System.out.println("index of str2 in str1 at occurrence "+ n +" = "+ index);
}
public static int nthOccurrence(String str1, String str2, int n) {
String tempStr = str1;
int tempIndex = -1;
int finalIndex = 0;
for(int occurrence = 0; occurrence < n ; ++occurrence){
tempIndex = tempStr.indexOf(str2);
if(tempIndex==-1){
finalIndex = 0;
break;
}
tempStr = tempStr.substring(++tempIndex);
finalIndex+=tempIndex;
}
return --finalIndex;
}
}