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

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

    Should be simple:

    foreach( string s in "1,3,5-10,12".Split(',') ) 
    {
        // try and get the number
        int num;
        if( int.TryParse( s, out num ) )
        {
            yield return num;
            continue; // skip the rest
        }
    
        // otherwise we might have a range
        // split on the range delimiter
        string[] subs = s.Split('-');
        int start, end;
    
        // now see if we can parse a start and end
        if( subs.Length > 1 &&
            int.TryParse(subs[0], out start) &&
            int.TryParse(subs[1], out end) &&
            end >= start )
        {
            // create a range between the two values
            int rangeLength = end - start + 1;
            foreach(int i in Enumerable.Range(start, rangeLength))
            {
                yield return i;
            }
        }
    }
    

    Edit: thanks for the fix ;-)

提交回复
热议问题