Finding second occurrence of a substring in a string in Java
JavaStringSubstringIndexofJava Problem Overview
We are given a string, say, "itiswhatitis"
and a substring, say, "is"
.
I need to find the index of 'i'
when the string "is"
occurs a second time in the original string.
String.indexOf("is")
will return 2 in this case. I want the output to be 10 in this case.
Java Solutions
Solution 1 - Java
Use overloaded version of indexOf()
, which takes the starting index (fromIndex) as 2nd parameter:
str.indexOf("is", str.indexOf("is") + 1);
Solution 2 - Java
I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
Solution 3 - Java
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);
This overload starts looking for the substring from the given index.
Solution 4 - Java
You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy
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;
}
Solution 5 - Java
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());
Solution 6 - Java
i think a loop can be used.
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
Solution 7 - Java
if you want to find index for more than 2 occurrence:
public static int ordinalIndexOf(String fullText,String subText,int pos){
if(fullText.contains(subText)){
if(pos <= 1){
return fullText.indexOf(subText);
}else{
--pos;
return fullText.indexOf(subText, ( ordinalIndexOf(fullText,subText,pos) + 1) );
}
}else{
return -1;
}
}
Solution 8 - Java
It seems to be a good party... I'm in:
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;
}