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

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

    Below is the code I just put together to do this.. You can enter in the format like.. 1-2,5abcd,6,7,20-15,,,,,,

    easy to add-on for other formats

        private int[] ParseRange(string ranges)
        { 
            string[] groups = ranges.Split(',');
            return groups.SelectMany(t => GetRangeNumbers(t)).ToArray();
        }
    
        private int[] GetRangeNumbers(string range)
        {
            //string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
    
            int[] RangeNums = range
                .Split('-')
                .Select(t => new String(t.Where(Char.IsDigit).ToArray())) // Digits Only
                .Where(t => !string.IsNullOrWhiteSpace(t)) // Only if has a value
                .Select(t => int.Parse(t)) // digit to int
                .ToArray();
            return RangeNums.Length.Equals(2) ? Enumerable.Range(RangeNums.Min(), (RangeNums.Max() + 1) - RangeNums.Min()).ToArray() : RangeNums;
        }
    

提交回复
热议问题