Does C# have built-in support for parsing page-number strings?

前端 未结 11 960
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 18:09

Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that\'s a mixture of comma and das

11条回答
  •  孤城傲影
    2020-12-14 19:01

    Regex is not efficient as following code. String methods are more efficient than Regex and should be used when possible.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] inputs = {
                                     "001-005/015",
                                     "009/015"
                                 };
    
                foreach (string input in inputs)
                {
                    List numbers = new List();
                    string[] strNums = input.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string strNum in strNums)
                    {
                        if (strNum.Contains("-"))
                        {
                            int startNum = int.Parse(strNum.Substring(0, strNum.IndexOf("-")));
                            int endNum = int.Parse(strNum.Substring(strNum.IndexOf("-") + 1));
                            for (int i = startNum; i <= endNum; i++)
                            {
                                numbers.Add(i);
                            }
                        }
                        else
                            numbers.Add(int.Parse(strNum));
                    }
                    Console.WriteLine(string.Join(",", numbers.Select(x => x.ToString())));
                }
                Console.ReadLine();
    
            }
        }
    }
    

提交回复
热议问题