C# 判断字符串是否为数字
时间: 2023-11-15 12:56:47 浏览: 41
可以使用 C# 中的 TryParse 方法来判断字符串是否为数字。具体实现如下:
```
string str = "123";
int num;
bool isNumeric = int.TryParse(str, out num);
if (isNumeric)
{
Console.WriteLine("是数字");
}
else
{
Console.WriteLine("不是数字");
}
```
相关问题
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#判断字符串是否为4数字
C#中可以使用TryParse方法来判断一个字符串是否为4位数字。具体步骤如下:
1. 使用int.TryParse方法将字符串转换为整数类型。
2. 判断转换是否成功,如果成功则进一步判断是否为4位数。
以下是示例代码:
```csharp
string input = "1234";
int number;
if (int.TryParse(input, out number))
{
if (number >= 1000 && number <= 9999)
{
Console.WriteLine("字符串是一个4位数字");
}
else
{
Console.WriteLine("字符串不是一个4位数字");
}
}
else
{
Console.WriteLine("字符串不是一个数字");
}
```