获取第n个IndexOf字符串

时间:2015-05-07 11:11:22

标签: c#

我认为类字符串中的函数IndexOf只能返回字符串中char的第一次出现。

例如

 string foo="blahblahblah";
 int num=foo.IndexOf("l") would make num= 1.

但是我想知道是否有类似的功能可以这样工作:

 string foo="blahblahblah"
 int indexNumber=2;
 int num=foo.aFunction("l",indexNumber) would make num=5.
 indexNumber=3;
 num=foo.aFunction("l",indexNumber) would make num= 9.

依此类推,indexNumber表示它不应该返回第一个发生,而是它指示的那个。

你能指导我这个功能或代码来实现这个目标吗?

3 个答案:

答案 0 :(得分:2)

此扩展返回给定字符串的所有索引

public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
{
    int minIndex = str.IndexOf(searchstring);
    while (minIndex != -1)
    {
        yield return minIndex;
        minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
    }
}

具有以下结果

string foo = "blahblahblah";
var result = foo.AllIndexesOf("l"); // 1,5,9

答案 1 :(得分:1)

您可以调用indexOf方法的重载,在该方法中指定搜索的起点:

https://msdn.microsoft.com/en-us/library/7cct0x33%28v=vs.110%29.aspx

因此,一旦找到第一个索引,如果您使用该值开始从该点开始搜索以查找下一个indexOf。

编辑说这在fubo的答案中的代码中得到了证明。

答案 2 :(得分:0)

您可以使用正则表达式,Regex.Matches给出所有给定子串的集合:

string foo = "blahblahblah";
MatchCollection matches = Regex.Matches(foo, "l");

foreach (Match m in matches)
    Console.WriteLine(m.Index);