Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.indexOf for multiple results

Tags:

c#

.net

Let's say I have a text and I want to locate the positions of each comma. The string, a shorter version, would look like this:

string s = "A lot, of text, with commas, here and,there";

Ideally, I would use something like:

int[] i = s.indexOf(',');

but since indexOf only returns the first comma, I instead do:

List<int> list = new List<int>();
for (int i = 0; i < s.Length; i++)
{
   if (s[i] == ',')
      list.Add(i);
}

Is there an alternative, more optimized way of doing this?

like image 473
GuruMeditation Avatar asked Jul 28 '11 20:07

GuruMeditation


1 Answers

Here I got a extension method for that, for the same use as IndexOf:

public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
{
    int minIndex = str.IndexOf(searchstring);
    while (minIndex != -1)
    {
        yield return minIndex;
        minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
    }
}

so you can use

s.AllIndexesOf(","); // 5    14    27    37

https://dotnetfiddle.net/DZdQ0L

like image 147
fubo Avatar answered Oct 05 '22 23:10

fubo