string input = "a1b2c3";Regex regex = new Regex(@"\d+");string result = regex.Match(input).Value;2. 循环和 Char.IsDigit()

c#怎么获取字符串中的数字

来源:这里教程网 时间:2026-02-21 16:49:09 作者:

如何从 C# 字符串中提取数字

从 C# 字符串中提取数字可以通过以下几种方法实现:

1. 正则表达式

<code class="csharp">string input = "a1b2c3";
Regex regex = new Regex(@"\d+");
string result = regex.Match(input).Value;</code>

2. 循环和 Char.IsDigit()

<code class="csharp">string input = "a1b2c3";
string result = "";
foreach (char c in input)
{
    if (Char.IsDigit(c))
    {
        result += c;
    }
}</code>

3. int.TryParse()

此方法将尝试将字符串转换为整数,如果成功则返回 true,否则返回 false。

<code class="csharp">string input = "123";
int result;
bool success = int.TryParse(input, out result);</code>

4. String.Split() 和 int.Parse()

<code class="csharp">string input = "1,2,3";
string[] numbers = input.Split(',');
int[] results = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
    results[i] = int.Parse(numbers[i]);
}</code>

5. LINQ

<code class="csharp">string input = "a1b2c3";
int[] results = input.Where(c => Char.IsDigit(c)).Select(c => (int)char.GetNumericValue(c)).ToArray();</code>

根据具体需求,选择最合适的方法即可。

相关推荐