WEB开发网
开发学院软件开发C语言 c#你怎么判断一个字符串是否是数字? 阅读

c#你怎么判断一个字符串是否是数字?

 2010-09-30 22:38:46 来源:WEB开发网   
核心提示:今天在写代码时突然想起测试经常用Microsoft.VisualBasic.Information.IsNumeric判断 url参数是否为数字时的这个方法的效率.因为数字是字符串是直接使用的,所以不需要转型,c#你怎么判断一个字符串是否是数字?,也就没有用tryparse结果一测试吓一跳,这个方法的效率是如此的低,再

今天在写代码时突然想起测试经常用Microsoft.VisualBasic.Information.IsNumeric判断 url参数是否为数字时的这个方法的效率.

因为数字是字符串是直接使用的,所以不需要转型,也就没有用tryparse

结果一测试吓一跳,这个方法的效率是如此的低,再测试了下tryparse还不错,正则的也比较差,

没什么技术含量,看结果吧:

先拓展下字符串:

   public static class Common
    {
        //isDigit
        public static bool isNumberic1(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            foreach (char c in _string)
            {
                if (!char.IsDigit(c))//if(c<'0' || c>'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
                    return false;
            }
            return true;
        }
        //vb isnumberic
        public static bool isNumberic2(this string _string)
        {
            return !string.IsNullOrEmpty(_string) && Microsoft.VisualBasic.Information.IsNumeric(_string);
        }
        //try parese
        public static bool isNumberic3(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            int i = 0;
            return int.TryParse(_string, out i);
        }
        //try catch
        public static bool isNumberic4(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            try { int.Parse(_string); }
            catch { return false; }
            return true;
        }
        //regex
        public static bool isNumberic5(this string _string)
        {
            return !string.IsNullOrEmpty(_string) && Regex.IsMatch(_string, "^\\d+$");
        }
    }

1 2  下一页

Tags:怎么 判断 一个

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接