在c#中 判断字符串是否为纯数字;
时间: 2024-02-14 14:07:16 浏览: 31
在 C# 中,判断一个字符串是否为纯数字可以使用正则表达式或者内置函数的方法。
方法一:使用正则表达式
```csharp
using System.Text.RegularExpressions;
// 判断是否为纯数字
public bool IsNumeric(string str)
{
if (string.IsNullOrEmpty(str))
{
return false; // 字符串为空或 null
}
Regex regex = new Regex(@"^[0-9]+$");
return regex.IsMatch(str);
}
```
方法二:使用内置函数
```csharp
// 判断是否为纯数字
public bool IsNumeric(string str)
{
if (string.IsNullOrEmpty(str))
{
return false; // 字符串为空或 null
}
foreach (char c in str)
{
if (c < '0' || c > '9')
{
return false; // 包含非数字字符
}
}
return true;
}
```
以上两种方法都可以判断一个字符串是否为纯数字,可以根据实际情况选择使用。
相关问题
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("字符串不是一个数字");
}
```
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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)