如何在不同的字符串中找到一个字符串的所有下标
本文关键字:字符串 一个 下标 | 更新日期: 2023-09-27 18:05:44
我的问题很直接,我怎么能找到另一个字符串里面的字符串的所有索引?这是我写的代码,但问题是,它所做的只是返回完全相同的索引多次。
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();
}
我不知道这段代码有什么问题。我想我可能需要在下次搜索前提前索引
我猜您应该在第二个s.IndexOf
调用中添加1。
:
lastIndex = s.IndexOf(Search, lastIndex + 1);