2015-05-07 158 views
0

我认为函数IndexOf只能从类字符串中返回字符串中第一个字符的出现次数。获取第n个索引字符串

例如

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表明它不应该返回第一ocurrence

等等,但它被指示的那个。

你能指导我介绍一下这个功能或者代码来实现吗?

回答

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 
0

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

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

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