1

假设我有一个包含数字的字符串。我想检查这个数字是否是整数。

例子

IsInteger("sss") => false 

IsInteger("123") => true

IsInterger("123.45") =>false
4

3 回答 3

17

你可以使用int。尝试解析。如果它可以解析字符串并将您的 out 参数设置为值,它将返回一个布尔值

 int val;
if(int.TryParse(inputString, out val))
{
    //dosomething
}
于 2008-10-11T13:56:02.803 回答
4

您可以使用两个直接选项。

选项 1 -首选- 使用Int32.TryParse

int res;
Console.WriteLine(int.TryParse("sss", out res));
Console.WriteLine(int.TryParse("123", out res));
Console.WriteLine(int.TryParse("123.45", out res));
Console.WriteLine(int.TryParse("123a", out res));

这输出:

False
True
False
False

选项 2 - 使用正则表达式

Regex pattern = new Regex("^-?[0-9]+$", RegexOptions.Singleline);
Console.WriteLine(pattern.Match("sss").Success);
Console.WriteLine(pattern.Match("123").Success);
Console.WriteLine(pattern.Match("123.45").Success);
Console.WriteLine(pattern.Match("123a").Success);

这输出:

False
True
False
False
于 2008-10-11T14:11:47.080 回答
2

你可以使用System.Int32.TryParse并做这样的事情......

string str = "10";
int number = 0;
if (int.TryParse(str, out number))
{
    // True
}
else
{
    // False
}
于 2008-10-11T14:00:27.320 回答