views:

212

answers:

3

Hello,

Basically I need to do String.IndexOf() and I need to get array of indexes from the source string.

Is there easy way to get array of indexes?

Before asking this question I have Googled a lot, but have not found easy solution to solve this simple problem.

+8  A: 

How about this extension method:

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

Note that when looking for "AA" in "XAAAY" this code will now only yield 1.

If you really need an array, call ToArray() on the result. (This is assuming .NET 3.5 and hence LINQ support.)

Jon Skeet
Could you please adjust it, so that it would return only 1
Daniil Harik
instead of advancing by 1, advance by the length of the needle -- to use Jon's nomenclature :)
Erich Mirabal
Exactly - but it can be slightly tricky to work out exactly where to do that :) I've fixed the code.
Jon Skeet
+1  A: 

You would have to loop, I suspect:

        int start = 0;
        string s = "abcdeafghaji";
        int index;
        while ((index = s.IndexOf('a', start)) >= 0)
        {
            Console.WriteLine(index);
            start = index + 1;
        }
Marc Gravell
+2  A: 
    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>();
          }
    }
Prashant
How would I do it, if I needed chChar to be string?Thank You.
Daniil Harik
Let me check on it..
Prashant