Remove text after a string occurrence

后端 未结 5 1106
温柔的废话
温柔的废话 2021-01-19 05:38

I have a string that has the following format:

string sample = \"A, ABC, 1, ACS,,\"

As you can see, there are 5 occurences of the ,

5条回答
  •  长情又很酷
    2021-01-19 06:30

    If you use the GetNthIndex method from this question, you can use String.Substring:

    public int GetNthIndex(string s, char t, int n)
    {
        int count = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == t)
            {
                count++;
                if (count == n)
                {
                    return i;
                }
            }
        }
        return -1;
    }
    

    So you could do the following:

    string sample = "A, ABC, 1, ACS,,";
    int index = GetNthIndex(sample, ',', 4);
    string result = sample.Substring(0, index);
    

提交回复
热议问题