Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 dash-delimited.

Something like this:

1,3,5-10,12

What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice:

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

I just want to avoid rolling my own if there's an easy way to do it.

like image 772
Mark Biek Avatar asked Sep 02 '08 17:09

Mark Biek


People also ask

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .

Does hep C go away?

It is highly curable ... Direct-acting antiviral medications — given over a 12-week period — actually can cure early acute hepatitis C better than 90% of the time.


2 Answers

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 ;-)

like image 170
Keith Avatar answered Sep 19 '22 11:09

Keith


It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.

Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.

Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like "1-2-3" or something.)

like image 44
Daniel Jennings Avatar answered Sep 20 '22 11:09

Daniel Jennings