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

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

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

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

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


当前回答

如果是单个字符串:

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

如果是字符串列表:

if (lstStr.All(s => s.All(Char.IsDigit)))
{
  // List of strings contains only digits
}

其他回答

您可以尝试使用正则表达式,通过使用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;
        }
    }
}

问候

另一种方法!

string str = "12345";
bool containsOnlyDigits = true;
try { if(Convert.ToInt32(str) < 0){ containsOnlyDigits = false; } }
catch { containsOnlyDigits = false; }

在这里,如果Convert.ToInt32(str)语句失败,则字符串不仅仅包含数字。另一种可能性是,如果字符串具有“-12345”,并成功转换为-12345,则会检查转换后的数字是否小于零。

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

返回str.All (char.IsDigit);

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

这应该可以工作:

Regex.IsMatch("124", "^[0-9]+$", RegexOptions.Compiled)

int。解析或int。TryParse并不总是有效,因为字符串可能包含int类型所能容纳的更多数字。

如果你要做这个检查不止一次,使用一个编译过的正则表达式是有用的——第一次会花费更多的时间,但之后会更快。

如果是单个字符串:

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

如果是字符串列表:

if (lstStr.All(s => s.All(Char.IsDigit)))
{
  // List of strings contains only digits
}