获取字符串第 n 次出现的索引? [英] Get the index of the nth occurrence of a string?
问题描述
除非我遗漏了一个明显的内置方法,否则获取字符串中第 n 次出现的最快方法是什么?
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?
我意识到我可以循环IndexOf 方法通过在循环的每次迭代更新其起始索引.但这样做对我来说似乎很浪费.
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.
推荐答案
这基本上就是您需要做的——或者至少,这是最简单的解决方案.所有你会浪费"的是 n 次方法调用的成本——如果你考虑一下,你实际上不会检查任何案例两次.(IndexOf 将在找到匹配项后立即返回,您将从它停止的地方继续前进.)
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.)
这篇关于获取字符串第 n 次出现的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!