我知道一些方法来检查字符串是否只包含数字: 正则表达式,int。解析,tryparse,循环等等。

谁能告诉我最快的方法是什么?

我只需要检查值,不需要实际解析它。

通过“数字”,我是指具体的ASCII数字:0 1 2 3 4 5 6 7 8 9。

如果字符串是数字,这个问题与Identify不同,因为这个问题不仅是关于如何识别,而且是关于识别的最快方法是什么。


当前回答

你可以在一行LINQ语句中做到这一点。好吧,我知道这不一定是最快的,所以从技术上讲并没有回答这个问题,但它可能是最容易写的:

str.All(c => c >= '0' && c <= '9')

其他回答

你可以使用LINQ简单地做到这一点:

返回str.All (char.IsDigit);

. all为空字符串返回true,为空字符串抛出异常。 char。IsDigit对所有Unicode数字字符都是true。

试试下面的代码:

bool isDigitsOnly(string str)
{
   try
   {
      int number = Convert.ToInt32(str);
      return true;
   }
   catch (Exception)
   {
      return false;
   }
}

下面是一些基于相同字符串的1000000次解析的基准测试:

更新发布数据:

IsDigitsOnly: 384588
TryParse:     639583
Regex:        1329571

下面是代码,看起来IsDigitsOnly更快:

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;
    }
}

当然值得注意的是,TryParse确实允许前导/尾随空白以及区域性特定的符号。弦的长度也有限制。

可能最快的方法是:

myString.All(c => char.IsDigit(c))

注意:如果你的字符串是空的,它将返回True,这是不正确的(如果你不认为空是有效的数字/数字)

您可以尝试使用正则表达式,通过使用c#中的. ismatch(字符串输入,字符串模式)方法测试输入字符串是否只有数字(0-9)。

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;
        }
    }
}

问候