获取第n个字符串出现的索引? [英] Get the index of the nth occurrence of a string?

查看:110
本文介绍了获取第n个字符串出现的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我错过了一个明显的内置方法,在字符串中出现 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆