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

前端 未结 11 948
隐瞒了意图╮
隐瞒了意图╮ 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:04

    My solution:

    • return list of integers
    • reversed/typo/duplicate possible: 1,-3,5-,7-10,12-9 => 1,3,5,7,8,9,10,12,11,10,9 (used when you want to extract, repeat pages)
    • option to set total of pages: 1,-3,5-,7-10,12-9 (Nmax=9) => 1,3,5,7,8,9,9
    • autocomplete: 1,-3,5-,8 (Nmax=9) => 1,3,5,6,7,8,9,8

          public static List pageRangeToList(string pageRg, int Nmax = 0)
      {
          List ls = new List();
          int lb,ub,i;
          foreach (string ss in pageRg.Split(','))
          {
              if(int.TryParse(ss,out lb)){
                  ls.Add(Math.Abs(lb));
              } else {
                  var subls = ss.Split('-').ToList();
                  lb = (int.TryParse(subls[0],out i)) ? i : 0;
                  ub = (int.TryParse(subls[1],out i)) ? i : Nmax;
                  ub = ub > 0 ? ub : lb; // if ub=0, take 1 value of lb
                  for(i=0;i<=Math.Abs(ub-lb);i++) 
                      ls.Add(lb 0 ? Nmax : ls.Max(); // real Nmax
          return ls.Where(s => s>0 && s<=Nmax).ToList();
      }
      

提交回复
热议问题