Fastest way to check if string contains only digits

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

    Try this code:

    bool isDigitsOnly(string str)
    {
       try
       {
          int number = Convert.ToInt32(str);
          return true;
       }
       catch (Exception)
       {
          return false;
       }
    }
    
    0 讨论(0)
  • 2020-12-04 09:53

    Another approach!

    string str = "12345";
    bool containsOnlyDigits = true;
    try { Convert.ToInt32(str); }
    catch { containsOnlyDigits = false; }
    
    0 讨论(0)
提交回复
热议问题