C#判断是否为数字
在C#中,可以使用以下方法来判断一个字符串是否为数字:
- 使用TryParse方法:
string input = "123";
int number;
bool isNumber = int.TryParse(input, out number);
if(isNumber)
{
Console.WriteLine("输入的字符串是数字");
}
else
{
Console.WriteLine("输入的字符串不是数字");
}
- 使用正则表达式:
string input = "123";
Regex regex = new Regex(@"^\d+$");
bool isNumber = regex.IsMatch(input);
if(isNumber)
{
Console.WriteLine("输入的字符串是数字");
}
else
{
Console.WriteLine("输入的字符串不是数字");
}
其中,正则表达式\d表示匹配数字,+表示匹配一次或多次。^和$分别表示匹配字符串的开头和结尾
原文地址: https://www.cveoy.top/t/topic/hgF7 著作权归作者所有。请勿转载和采集!