如何检查我的字符串是否只是数字

Gol*_*old 21 c#

我如何检查我的字符串是否只包含数字?

我不记得了.有什么像isnumeric?

Jon*_*ood 63

只需检查每个角色.

bool IsAllDigits(string s)
{
    foreach (char c in s)
    {
        if (!char.IsDigit(c))
            return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

或者使用LINQ.

bool IsAllDigits(string s)
{
    return s.All(char.IsDigit);
}
Run Code Online (Sandbox Code Playgroud)

如果您想知道输入到程序中的值是否表示有效的整数值(在范围内int),您可以使用TryParse().请注意,此方法与检查字符串是否仅包含数字不同.

bool IsAllDigits(string s)
{
    return int.TryParse(s, out int i);
}
Run Code Online (Sandbox Code Playgroud)


Adr*_*der 10

您可以使用Regexint.TryParse.

另请参见C#等效的VB的IsNumeric()

  • 我不建议使用`int.TryParse`或`long.TryParse`,因为它们可以溢出. (4认同)

Tal*_*ner 7

对于非数字字符串,int.TryParse()方法将返回false

  • 如果字符串太长,它也会抛出溢出异常. (7认同)

Che*_*hen 5

你的问题不明确..在字符串中是允许的吗?被¼允许吗?

string source = GetTheString();

//only 0-9 allowed in the string, which almost equals to int.TryParse
bool allDigits = source.All(char.IsDigit); 
bool alternative = int.TryParse(source,out result);

//allow other "numbers" like ¼
bool allNumbers = source.All(char.IsNumber);
Run Code Online (Sandbox Code Playgroud)


Nik*_*kis 5

如果你想使用正则表达式,你将不得不使用这样的东西:

string regExPattern = @"^[0-9]+$";
System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regExPattern);
return pattern.IsMatch(yourString);
Run Code Online (Sandbox Code Playgroud)