2015-05-07 156 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);