我知道一些方法来检查字符串是否只包含数字: 正则表达式,int。解析,tryparse,循环等等。
谁能告诉我最快的方法是什么?
我只需要检查值,不需要实际解析它。
通过“数字”,我是指具体的ASCII数字:0 1 2 3 4 5 6 7 8 9。
如果字符串是数字,这个问题与Identify不同,因为这个问题不仅是关于如何识别,而且是关于识别的最快方法是什么。
我知道一些方法来检查字符串是否只包含数字: 正则表达式,int。解析,tryparse,循环等等。
谁能告诉我最快的方法是什么?
我只需要检查值,不需要实际解析它。
通过“数字”,我是指具体的ASCII数字:0 1 2 3 4 5 6 7 8 9。
如果字符串是数字,这个问题与Identify不同,因为这个问题不仅是关于如何识别,而且是关于识别的最快方法是什么。
当前回答
函数的空验证:
public static bool IsDigitsOnly(string str)
{
return !string.IsNullOrEmpty(str) && str.All(char.IsDigit);
}
其他回答
可能最快的方法是:
myString.All(c => char.IsDigit(c))
注意:如果你的字符串是空的,它将返回True,这是不正确的(如果你不认为空是有效的数字/数字)
该字符已经有一个IsDigit(char c),它是这样做的:
public static bool IsDigit(char c)
{
if (!char.IsLatin1(c))
return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
if ((int) c >= 48)
return (int) c <= 57;
else
return false;
}
你可以简单地这样做:
var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);
函数的空验证:
public static bool IsDigitsOnly(string str)
{
return !string.IsNullOrEmpty(str) && str.All(char.IsDigit);
}
public bool CheckforDigits(string x)
{
int tr;
return x.All(r=> int.TryParse(r.ToString(), out tr));
}
您可以尝试使用正则表达式,通过使用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;
}
}
}
问候