【问题标题】:How can I find all of the indices of a string in a different string?如何在不同的字符串中找到字符串的所有索引?
【发布时间】:2013-03-13 14:51:25
【问题描述】:

我的问题很简单,我怎样才能在另一个字符串中找到一个字符串的所有索引?这是我编写的代码,但问题是它所做的只是多次返回完全相同的索引。这是:

    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();
    }

我不知道这段代码有什么问题。我想我可能需要在下一次搜索之前推进索引。

【问题讨论】:

    标签: c# visual-studio-2010 indexof indices


    【解决方案1】:

    我的猜测是你应该在你的第二个s.IndexOf 调用中加 1。

    即:

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

    【讨论】:

    • 我所做的一切都没有注意到我必须推进索引,感谢您的帮助,现在可以关闭了。
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2021-12-18
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2011-03-14
    • 2012-05-26
    相关资源
    最近更新 更多