How to get the Index of second comma in a string

落花浮王杯 提交于 2019-12-03 10:25:07

You have to use code like this.

int index = s.IndexOf(',', s.IndexOf(',') + 1);

You may need to make sure you do not go outside the bounds of the string though. I will leave that part up to you.

I just wrote this Extension method, so you can get the nth index of any substring in a string

public static class Extensions
{
    public static int IndexOfNth(this string str, string value, int nth = 1)
    {
        if (nth <= 0)
            throw new ArgumentException("Can not find the zeroth index of substring in string. Must start with 1");
        int offset = str.IndexOf(value);
        for (int i = 1; i < nth; i++)
        {
            if (offset == -1) return -1;
            offset = str.IndexOf(value, offset + 1);
        }
        return offset;
    }
}

Note: In this implementation I use 1 = first, instead of a 0 based index. This can easily be changed to use 0 = first, by adding a nth++; to the beginning, and changing the error message for clarity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!