Search code examples
c#.netstringindexingindexof

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.


Solution

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