如何在c#中添加字符串的所有数字到数组中

本文关键字:数字 数组 字符串 添加 | 更新日期: 2023-09-27 18:06:06

所以我一直试图从字符串中获得所有的数字并将它们放入数组,但我失败了:(

String: "有10个苹果,8个葡萄,120个橙子和6363个柠檬。"

期望结果:

Fruits[0]=10
Fruits[1]=8
Fruits[2]=120
Fruits[3]=6363

请帮助我:),提前谢谢你~

如何在c#中添加字符串的所有数字到数组中

把句子分成几个词。然后,检查每个单词是否可以转换为整数;如果可以,将其添加到列表中:

       string sentence = "there's 10 Apples, 8 Grapes, 120 Oranges, and 6363 Lemons.";
       string[] words = sentence.Split(' ');
       List<int> fruits = new List<int>();
       for (int index = 0; index < words.Count(); index++)
       {
            int number;
            if (int.TryParse(words[index], out number))
            {
                fruits.Add(number);
            }
        }
var sentence = "there's 10 Apples, 8 Grapes, 120 Oranges, and 6363 Lemons.";
Regex rgx = new Regex("'d+");
foreach (Match match in rgx.Matches(sentence))
     Console.WriteLine("Found '{0}'", match.Value);