Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of the nth occurrence of a string?

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.

like image 640
PeteT Avatar asked Oct 09 '08 10:10

PeteT


People also ask

How do you find the index of all occurrences in a string?

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.

How do you find the nth character in a string?

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.

How do you find the nth position of a string in Python?

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.


2 Answers

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.

like image 139
Alexander Prokofyev Avatar answered Oct 12 '22 11:10

Alexander Prokofyev


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.)

like image 41
Jon Skeet Avatar answered Oct 12 '22 10:10

Jon Skeet