csharp获取字符串中的数字
时间: 2024-05-14 20:17:28 浏览: 19
可以使用正则表达式来获取字符串中的数字。以下是一个示例代码:
```csharp
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "abc123def456ghi789";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
```
这个代码会输出字符串中的所有数字,即:
```
123
456
789
```
相关问题
C# 如何提取字符串中的数字
在 C# 中,可以使用正则表达式来提取字符串中的数字。下面是一个简单的示例代码:
```csharp
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string input = "abc123def456";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches) {
Console.WriteLine(match.Value);
}
}
}
```
上述代码中,使用了 `\d+` 的正则表达式来匹配字符串中的数字,然后使用 `Regex.Matches` 方法来获取所有匹配的结果,最后使用 `foreach` 循环打印出每个匹配到的数字。
C#比较两串字符串中第八位数字的大小
你可以先使用 `Substring()` 方法获取两个字符串中的第八位数字,再将其转为整数类型进行比较。
例如,比较字符串 `str1` 和 `str2` 中第八位数字的大小,可以这样做:
```csharp
string str1 = "AB123456C";
string str2 = "DE987654F";
int num1 = int.Parse(str1.Substring(7, 1)); // 获取第八位数字并转为整数类型
int num2 = int.Parse(str2.Substring(7, 1));
if (num1 > num2) {
Console.WriteLine("str1 中第八位数字大于 str2 中第八位数字");
} else if (num1 < num2) {
Console.WriteLine("str1 中第八位数字小于 str2 中第八位数字");
} else {
Console.WriteLine("str1 中第八位数字等于 str2 中第八位数字");
}
```
这里使用了 `Substring()` 方法获取字符串中的一部分子串,再使用 `int.Parse()` 方法将第八位数字转为整数类型进行比较。