Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding multiple indexes from source string

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.

like image 489
Daniil Harik Avatar asked Apr 20 '09 10:04

Daniil Harik


1 Answers

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.)

like image 158
Jon Skeet Avatar answered Oct 26 '22 21:10

Jon Skeet