从源字符串中查找多个索引

Dan*_*rik 6 .net c# string algorithm

基本上我需要做String.IndexOf(),我需要从源字符串中获取索引数组.

有没有简单的方法来获取索引数组?

在提出这个问题之前,我已经搜索了很多,但还没有找到解决这个简单问题的简单解决方案.

Jon*_*eet 16

这个扩展方法怎么样:

public static IEnumerable<int> IndexesOf(this string haystack, string needle)
{
    int lastIndex = 0;
    while (true)
    {
        int index = haystack.IndexOf(needle, lastIndex);
        if (index == -1)
        {
            yield break;
        }
        yield return index;
        lastIndex = index + needle.Length;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在"XAAAY"中查找"AA"时,此代码现在只会产生1.

如果你真的需要一个数组,请调用ToArray()结果.(这假设是.NET 3.5,因此支持LINQ.)


Mar*_*ell 6

我怀疑你必须循环:

        int start = 0;
        string s = "abcdeafghaji";
        int index;
        while ((index = s.IndexOf('a', start)) >= 0)
        {
            Console.WriteLine(index);
            start = index + 1;
        }
Run Code Online (Sandbox Code Playgroud)


Pra*_*dda 6

    var indexs = "Prashant".MultipleIndex('a');

//Extension Method's Class
    public static class Extensions
    {
         static int i = 0;

         public static int[] MultipleIndex(this string StringValue, char chChar)
         {

           var indexs = from rgChar in StringValue
                        where rgChar == chChar && i != StringValue.IndexOf(rgChar, i + 1)
                        select new { Index = StringValue.IndexOf(rgChar, i + 1), Increament = (i = i + StringValue.IndexOf(rgChar)) };
            i = 0;
            return indexs.Select(p => p.Index).ToArray<int>();
          }
    }
Run Code Online (Sandbox Code Playgroud)