所以我一直试图从字符串中获取所有数字并将它们放入数组但是我失败了:(
字符串:“有10个苹果,8个葡萄,120个橘子和6363个柠檬。”
期望的结果:
Fruits[0]=10
Fruits[1]=8
Fruits[2]=120
Fruits[3]=6363
请帮帮我:)并提前谢谢你〜
答案 0 :(得分:0)
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);
答案 1 :(得分:0)
将句子分成单词。然后,检查每个单词以查看它是否可以转换为整数;如果可以,将其添加到列表中:
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);
}
}