Unless I am missing an obvious built-in method, what is the quickest way to get the nth occurrence of a string within a string?
I realize that I could loop the IndexOf method by updating its start index on each iteration of the loop. But doing it this way seems wasteful to me.
Using indexOf() and lastIndexOf() method To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.
Use the charAt() method to get the nth character in a string, e.g. str. charAt(1) gets the second character in the string. The only parameter the charAt method takes is the index of the character to be returned. If the index does not exist in the string, an empty string is returned.
You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.
You really could use the regular expression /((s).*?){n}/
to search for n-th occurrence of substring s
.
In C# it might look like this:
public static class StringExtender { public static int NthIndexOf(this string target, string value, int n) { Match m = Regex.Match(target, "((" + Regex.Escape(value) + ").*?){" + n + "}"); if (m.Success) return m.Groups[2].Captures[n - 1].Index; else return -1; } }
Note: I have added Regex.Escape
to original solution to allow searching characters which have special meaning to regex engine.
That's basically what you need to do - or at least, it's the easiest solution. All you'd be "wasting" is the cost of n method invocations - you won't actually be checking any case twice, if you think about it. (IndexOf will return as soon as it finds the match, and you'll keep going from where it left off.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With