2013-03-23 45 views
1

我的問題非常簡單,我如何找到另一個字符串中的所有字符串索引?這是我寫的代碼,但問題是它所做的只是多次返回完全相同的索引。這裏是:
如何查找不同字符串中的所有字符串索引?

public static int[] IndicesOf(this string s, string Search, int StartIndex) 
    { 
     List<int> indices = new List<int>(); 
     int lastIndex = 0; 
     lastIndex = s.IndexOf(Search); 
     while (lastIndex != -1) 
     { 
      indices.Add(lastIndex); 
      lastIndex = s.IndexOf(Search, lastIndex); 
     } 
     return indices.ToArray(); 
    } 

我不知道這段代碼有什麼問題。我想我可能需要在下一次搜索前推進索引。

回答

5

我的猜測是,你應該加1到你的第二個s.IndexOf電話。

即:

lastIndex = s.IndexOf(Search, lastIndex + 1); 
+0

所有我做過沒有注意到我不得不提前索引,感謝您的幫助,這個現在可以關閉。 – Jake 2013-03-23 22:05:00

相關問題