Fastest way to check if string contains only digits

后端 未结 20 842
挽巷
挽巷 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:32

    You can try using Regular Expressions by testing the input string to have only digits (0-9) by using the .IsMatch(string input, string pattern) method in C#.

    using System;
    using System.Text.RegularExpression;
    
    public namespace MyNS
    {
        public class MyClass
        {
            public void static Main(string[] args)
            {
                 string input = Console.ReadLine();
                 bool containsNumber = ContainsOnlyDigits(input);
            }
    
            private bool ContainOnlyDigits (string input)
            {
                bool containsNumbers = true;
                if (!Regex.IsMatch(input, @"/d"))
                {
                    containsNumbers = false;
                }
                return containsNumbers;
            }
        }
    }
    

    Regards

提交回复
热议问题