Fastest way to check if string contains only digits

后端 未结 20 821
挽巷
挽巷 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:31
    bool IsDigitsOnly(string str)
    {
        foreach (char c in str)
        {
            if (c < '0' || c > '9')
                return false;
        }
    
        return true;
    }
    

    Will probably be the fastest way to do it.

    0 讨论(0)
  • 2020-12-04 09:31

    This might be coming super late!, but I'm sure it will help someone, as it helped me.

            private static bool IsDigitsOnly(string str)
            {
                return str.All(c => c >= '0' && c <= '9');
            }
    
    0 讨论(0)
  • 2020-12-04 09:31

    if it is a single string :

    if (str.All(Char.IsDigit))
    {
      // string contains only digits
    }
    

    if it is a list of strings :

    if (lstStr.All(s => s.All(Char.IsDigit)))
    {
      // List of strings contains only digits
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-04 09:33

    What about char.IsDigit(myChar)?

    0 讨论(0)
  • 2020-12-04 09:35

    You could simply do this using LINQ

    return str.All(char.IsDigit);

    1. .All returns true for empty strings and exception for null strings.
    2. char.IsDigit is true for all Unicode characters.
    0 讨论(0)
提交回复
热议问题