Finding second occurrence of a substring in a string in Java
Solution 1
Use overloaded version of indexOf()
, which takes the starting index (fromIndex) as 2nd parameter:
str.indexOf("is", str.indexOf("is") + 1);
Solution 2
I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
Solution 3
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
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
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());
Comments
-
AmanArora about 3 years
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. -
Pravat Panda over 10 yearswhat if the occurence is more than twice?
-
Jeroen Vannevel over 10 yearsThen nothing special happens, it will still take the second occurence.
-
Pravat Panda over 10 yearswhat about the index of third occurence!
-
Jeroen Vannevel over 10 yearsWhat about it? The question was to find the second occurence.
-
Pravat Panda over 10 yearsi mean what if 10 occcurences are there in the string
-
Juha Untinen almost 10 years@PravatPanda: I guess you want to know how to get the third occurence? Then you could just continue the code in Jeroen's answer and add a third
string.indexOf("is", second + 1);
although it would probably be better to make a method that returns the Nth indexOf -
Pravat Panda almost 10 years@JuhaUntinen recursion??
-
sofs1 over 5 yearsThis is ingenious.
-
Hassan Jamil about 3 yearsNice solution, I found. Thank you Hasnaa!
-
Osmar over 2 yearsNice and clear, thanks!