Finding second occurrence of a substring in a string in Java

AmanArora picture AmanArora · Sep 26, 2013 · Viewed 135.2k times · Source

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.

Answer

Rohit Jain picture Rohit Jain · Sep 26, 2013

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);