日期:2014-05-20  浏览次数:20436 次

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

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

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

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

 

先拓展下字符串:

 

code 
 
C# code
  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))
                    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;
            int i = 0;
            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+$");
        }
    } 


测试的代码:

 

code 
C# code
    class Program 
    {
        static void Main(string[] args)
        {

            Test("1234");
            Test("1234a");
            Test("a1234");
            Test("");
            Test(null);
           
        }

        static void Test(string str)
        {
            bool res1 = false, res2 = false, res3 = false, res4 = false, res5 = false;
            Stopwatch wat = new Stopwatch();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res1 = str.isNumberic1();
            }
            wat.Stop();
            Console.WriteLine("isDigit      {0}:{1},{2}", str, wat.ElapsedMilliseconds, res1);

            wat.Reset();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res2= str.isNumberic2();
            }
            wat.Stop();
            Console.WriteLine("isNumberic  {0}:{1},{2}", str, wat.ElapsedMilliseconds, res2);

            wat.Reset();
            wat.Start();