Remove text after a string occurrence

后端 未结 5 1100
温柔的废话
温柔的废话 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:11

    Assuming that you want to return the full string if there aren't enough commas to satisfy the count

    String fx(String str, Int32 commaCount) 
        {
            if (String.IsNullOrEmpty(str)) return str;
            var i = 0;
            var strLength = str.Length;
            while ((commaCount-- > 0) && (i != -1) && (i < strLength)) i = str.IndexOf(",", i + 1);
            return (i == -1 ? str : str.Substring(i));
        }
    

提交回复
热议问题