c# 仅从包含数字和单词的字符串列表中获取数字

我有一个字符串列表(单词--数字)前(汉堡 5 美元)。我只需要从列表中的每个字符串中提取数字并创建新的 int 列表。



Helenr
浏览 147回答 4
4回答

慕容3067478

有几种方法可以做到这一点,例如 Regex 和 Linq。对于短字符串,您可以使用 Linq,例如:public static void Main(){    var myStringValue = "burger 5$";    var numbersArray = myStringValue.ToArray().Where(x => char.IsDigit(x));    foreach (var number in numbersArray)    {        Console.WriteLine(numbersArray);    }}

catspeake

如果您查看Regex.Split,数字文章。你会在那里找到答案。修改后的代码可能看起来像var source = new List<string> {&nbsp; &nbsp; "burger 5$",&nbsp; &nbsp; "pizza 6$",&nbsp; &nbsp; "roll 1$ and salami 2$"};var result = new List<int>();foreach (var input in source){&nbsp; &nbsp; var numbers = Regex.Split(input, @"\D+");&nbsp; &nbsp; foreach (string number in numbers)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (Int32.TryParse(number, out int value))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.Add(value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}希望能帮助到你。彼得

富国沪深

您可以查看并使用此代码解决问题:&nbsp; List<string> word_number = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<int> number = new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; word_number.Add("burger 5$");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; word_number.Add("hamburger 6$");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; word_number.Add("burger 12$");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var item in word_number)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] parts = item.Split(' ');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] string_number = parts[1].Split('$');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; number.Add(Convert.ToInt16(string_number[0]));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(string_number[0]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }

白衣染霜花

使用linq和Regex:List<string> list = new List<string>(){"burger 5$","ab12c","12sc34","sd3d5"};Regex nonDigits = new Regex(@"[^\d]");&nbsp; &nbsp;List<string> list2 = list.Select(l => nonDigits.Replace(l, "")).ToList();
打开App,查看更多内容
随时随地看视频慕课网APP