C#有内置的解析页面数字符串支持? [英] Does C# have built-in support for parsing page-number strings?

查看:103
本文介绍了C#有内置的解析页面数字符串支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#有内置支持用于解析页码的字符串?由页码,我的意思是你可能会进入一个打印对话框,这是逗号和破折号分隔的混合物格式

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.

事情是这样的:

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.

推荐答案

应该是简单的:

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

修改感谢修复;-)

这篇关于C#有内置的解析页面数字符串支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆