.indexOf for multiple results

后端 未结 4 770
礼貌的吻别
礼貌的吻别 2021-01-06 03:05

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,          


        
4条回答
  •  梦谈多话
    2021-01-06 03:30

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

    public static IEnumerable 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

提交回复
热议问题