从字符串中提取多个整数并存储为int
本文关键字:存储 int 整数 字符串 提取 | 更新日期: 2023-09-27 17:50:01
我知道这将提取数字并存储为int -
string inputData = "sometex10";
string data = System.Text.RegularExpressions.Regex.Match(inputData, @"'d+").Value;
int number1 = Convert.ToInt32(data);
我试图从字符串中提取多个数字,例如- 10 + 2 + 3,并将这些存储为单独的整数。注意:用户将输入的数字数量是未知的。如有任何建议,非常感谢
您可以使用LINQ一行代码:
var numbers = Regex.Matches(inputData, @"'d+").Select(m => int.Parse(m.Value)).ToList();
ToArray()
。C# program that uses Regex.Split
引用:http://www.dotnetperls.com/regex-split
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
//
// String containing numbers.
//
string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer.";
//
// Get all digit sequence as strings.
//
string[] digits = Regex.Split(sentence, @"'D+");
//
// Now we have each number string.
//
foreach (string value in digits)
{
//
// Parse the value to get the number.
//
int number;
if (int.TryParse(value, out number))
{
Console.WriteLine(number);
}
}
}
}
你可以这样写:
string inputData = "sometex10";
List<int> numbers = new List<int>();
foreach(Match m in Regex.Matches(inputData, @"'d+"))
{
numbers.Add(Convert.ToInt32(m.Value));
}
这将把整数存储在列表numbers