How to get the Index of second comma in a string

前端 未结 2 748
不知归路
不知归路 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 01:09

    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.

    0 讨论(0)
提交回复
热议问题