Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding second occurrence of a substring in a string in Java

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.

like image 500
AmanArora Avatar asked Sep 26 '13 18:09

AmanArora


People also ask

How do you find the nth occurrence of a string in Java?

To find the index of nth occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times. There could be a requirement in your Java application, that you have to find the position of the nth occurrence of str2 in str1 .

How do you index the second comma of a string?

You have to use code like this. int index = s. IndexOf(',', s. IndexOf(',') + 1);


2 Answers

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

str.indexOf("is", str.indexOf("is") + 1); 
like image 118
Rohit Jain Avatar answered Sep 18 '22 23:09

Rohit Jain


I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()

StringUtils.ordinalIndexOf("Java Language", "a", 2) 
like image 25
To Kra Avatar answered Sep 22 '22 23:09

To Kra