Jak*_*ake 1 c# indexof visual-studio-2010 indices
我的问题很简单,如何在另一个字符串中找到字符串的所有索引?这是我写的代码,但问题是它所做的只是多次返回完全相同的索引.这里是:
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();
}
Run Code Online (Sandbox Code Playgroud)
我不知道这段代码有什么问题.我想我可能需要在下一次搜索之前推进索引.
我的猜测是你应该在你的第二个s.IndexOf电话中加1 .
那是:
lastIndex = s.IndexOf(Search, lastIndex + 1);
Run Code Online (Sandbox Code Playgroud)