Extract multiple integers from string and store as int

◇◆丶佛笑我妖孽 提交于 2020-11-29 10:36:19

问题


I know that this will extract the number and store as int -

string inputData = "sometex10";

string  data = System.Text.RegularExpressions.Regex.Match(inputData, @"\d+").Value;
int  number1 = Convert.ToInt32(data);

I am trying to extract multiple numbers from a string eg- 10 + 2 + 3 and store these as separate integers. note : the amount of numbers the user will type in is unknow. Any suggestions much appreciated thanks


回答1:


You can use a LINQ one-liner:

var numbers = Regex.Matches(inputData, @"\d+").Select(m => int.Parse(m.Value)).ToList();

Or use ToArray() if you prefer an array instead of a list.




回答2:


C# program that uses Regex.Split

Referencing : 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);
        }
    }
    }
}



回答3:


You can use something like this:

string inputData = "sometex10";
List<int> numbers = new List<int>();
foreach(Match m in Regex.Matches(inputData, @"\d+"))
{
    numbers.Add(Convert.ToInt32(m.Value));
}

This will store the integers in the list numbers



来源:https://stackoverflow.com/questions/30328781/extract-multiple-integers-from-string-and-store-as-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!