从C#中的字符串中获取数字,可以使用正则表达式或者遍历字符串的方式。以下是两种方法的示例代码:
方法一:使用正则表达式
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string input = "abc123def456";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
方法二:遍历字符串
using System;
class Program
{
static void Main(string[] args)
{
string input = "abc123def456";
string result = "";
foreach (char c in input)
{
if (Char.IsDigit(c))
{
result += c;
}
}
Console.WriteLine(result);
}
}
这两种方法都可以从C#中的字符串中获取数字,具体使用哪种方法需要根据实际情况进行选择。
领取专属 10元无门槛券
手把手带您无忧上云