Similar to a question posted here, am looking for a solution in Java.
That is, how to find the index of nth occurrence of a character/string from a string?
Example: "/folder1/folder2/folder3/". In this case, if I ask for 3rd occurrence of slash (/), it appears before folder3, and I expect to return this index position. My actual intention is to substring it from nth occurrence of a character.
Is there any convenient/ready-to-use method available in Java API or do we need to write a small logic on our own to solve this?
Also,
If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf
, otherwise, here's an implementation:
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
This post has been rewritten as an article here.