c# 判断字符串是否是数字
时间: 2023-07-12 13:49:49 浏览: 137
你可以使用 C# 中的 TryParse 方法来判断一个字符串是否为数字,示例代码如下:
```csharp
string str = "1234";
int num;
bool isNumeric = int.TryParse(str, out num);
if (isNumeric)
{
Console.WriteLine("字符串是数字");
}
else
{
Console.WriteLine("字符串不是数字");
}
```
如果字符串 str 是一个数字,TryParse 方法会将其转换为整数并返回 true,同时将转换后的值存储在 num 变量中。如果字符串不是数字,TryParse 方法会返回 false,num 变量的值为 0。
相关问题
C# 判断字符串是否为数字
可以使用 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;
}
```