Fastest way to check if string contains only digits

后端 未结 20 876
挽巷
挽巷 2020-12-04 09:07

I know a few ways how to check this. regex,int.parse,tryparse,looping.

can anyone tell me what is the fastest way to check?

the nee

20条回答
  •  半阙折子戏
    2020-12-04 09:40

    Here's some benchmarks based on 1000000 parses of the same string:

    Updated for release stats:

    IsDigitsOnly: 384588
    TryParse:     639583
    Regex:        1329571
    

    Here's the code, looks like IsDigitsOnly is faster:

    class Program
    {
        private static Regex regex = new Regex("^[0-9]+$", RegexOptions.Compiled);
    
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            string test = int.MaxValue.ToString();
            int value;
    
            watch.Start();
            for(int i=0; i< 1000000; i++)
            {
                int.TryParse(test, out value);
            }
            watch.Stop();
            Console.WriteLine("TryParse: "+watch.ElapsedTicks);
    
            watch.Reset();
            watch.Start();
            for (int i = 0; i < 1000000; i++)
            {
                IsDigitsOnly(test);
            }
            watch.Stop();
            Console.WriteLine("IsDigitsOnly: " + watch.ElapsedTicks);
    
            watch.Reset();
            watch.Start();
            for (int i = 0; i < 1000000; i++)
            {
                regex.IsMatch(test);
            }
            watch.Stop();
            Console.WriteLine("Regex: " + watch.ElapsedTicks);
    
            Console.ReadLine();
        }
    
        static bool IsDigitsOnly(string str)
        {
            foreach (char c in str)
            {
                if (c < '0' || c > '9')
                    return false;
            }
    
            return true;
        }
    }
    

    Of course it's worth noting that TryParse does allow leading/trailing whitespace as well as culture specific symbols. It's also limited on length of string.

提交回复
热议问题