How to get the Index of second comma in a string

前端 未结 2 753
不知归路
不知归路 2020-12-10 00:20

I have a string in an Array that contains two commas as well as tabs and white spaces. I\'m trying to cut two words in that string, both of them before the commas, I really

2条回答
  •  长情又很酷
    2020-12-10 00:46

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

    Note: To get the index of the first instance, use nth = 0.

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

提交回复
热议问题