C# 检测输入的值是否为数字
时间: 2024-03-22 17:40:14 浏览: 17
你可以使用 C# 的 TryParse 方法来检测输入的值是否为数字。示例如下:
```csharp
string input = Console.ReadLine();
int number;
if (int.TryParse(input, out number))
{
// 输入的值是数字
}
else
{
// 输入的值不是数字
}
```
上述代码中,`Console.ReadLine()` 用于读取用户的输入。`int.TryParse()` 方法将输入的值转换为整数,如果转换成功,则说明输入的值是数字,否则说明输入的值不是数字。
相关问题
C#判断字符串是否为数字
在C#中,有多种方法可以判断一个字符串是否为数字:
1. 使用Char.IsDigit()方法和Enumerable.All()方法:
```C#
public bool isPureNum(string str)
{
if (str == null || str.Length == 0)
{
return false;
}
bool isNumeric = str.All(char.IsDigit);
return isNumeric;
}
```
2. 使用Regex.IsMatch()方法和正则表达式:
```C#
public bool isPureNum(string str)
{
if (str == null || str.Length == 0)
{
return false;
}
bool isNumeric = System.Text.RegularExpressions.Regex.IsMatch(str, @"^\d$");
return isNumeric;
}
```
3. 使用ASCII码判断:
```C#
public bool isPureNum(string str)
{
if (str == null || str.Length == 0)
{
return false;
}
byte[] strBytes = Encoding.ASCII.GetBytes(str);
foreach (byte strByte in strBytes)
{
if (strByte < 48 || strByte > 57)
{
return false;
}
}
return true;
}
```
4. 使用TryParse()方法:
```C#
public bool isPureNum(string str)
{
if (str == null || str.Length == 0)
{
return false;
}
int num;
bool isNumeric = int.TryParse(str, out num);
return isNumeric;
}
```
C# 判断字符串是否为数字
可以使用 C# 中的 TryParse 方法来判断字符串是否为数字。具体实现如下:
```
string str = "123";
int num;
bool isNumeric = int.TryParse(str, out num);
if (isNumeric)
{
Console.WriteLine("是数字");
}
else
{
Console.WriteLine("不是数字");
}
```