Convert list to number range string

后端 未结 6 622
你的背包
你的背包 2020-12-05 19:45

This question is pretty much the opposite of this question: Does C# have built-in support for parsing page-number strings?

So given

1,3,5,6,7,8,9,10         


        
6条回答
  •  清歌不尽
    2020-12-05 20:43

    This should work pretty well, not tested for all cases though.

            string s = "1,2,3,4,5,7,8,9,10,11,12,13";
            string[] ints = s.Split(',');
            StringBuilder result = new StringBuilder();
    
            int num, last = -1;
            bool dash = false;
    
            for (int ii = 0; ii < ints.Length; ii++)
            {
                num = Int32.Parse(ints[ii]);
    
                if (num - last > 1)
                {
                    if (dash)
                    {
                        result.Append(last);
                        dash = false;
                    }
                    if (result.Length > 0)
                    {
                        result.Append(",");
                    }
                    result.Append(num);                    
                }
                else
                {
                    if (dash == false)
                    {
                        result.Append("-");
                        dash = true;
                    }
                }
    
                last = num;
    
                if (dash && ii == ints.Length - 1)
                {
                    result.Append(num);
                }
            }
    
            Console.WriteLine(result);
    

提交回复
热议问题