简体   繁体   中英

How can I pull all Numbers (as int) out of a string? c#

I have a long string, and I'd like to loop through it and pull out all the int values in order. This seems simple enough, but I can't seem to figure it out.

string raw = "I am a string and I have some numbers 3 45 333 2 39 inside of me 1839 9303, and I'd like to get these numbers into 9 -10 00  9e09 into a string[] or something else";

int[] justNumbers = raw.?????

Using C# .NET 3.5 and have access to Regex and Linq if necessary. Thanks.

Final result would be a long list of ints. ie

List<int> numbers = new List<int>();

WHAT I ENDED UP USING (NOT THE MOST EFFICIENT, BUT WORKED)

#region mysolution
        numbers = new List<int>();
        foreach (char item in raw)
        {
            if (item.ToString() == "0")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "1")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "2")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "3")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "4")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "5")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "6")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "7")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "8")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
            else if (item.ToString() == "9")
            {
                numbers.Add(Convert.ToInt32(item.ToString()));
            }
        }

        #endregion

Something along the lines of: (untested)

var items = raw.Split(' ');
var integers = new List<int>();
foreach(var i in items){
    int test = 0;
    if(int.TryParse(i, out test)){
        integers.add(test);
    }
}

EDIT : There is an overload of TryParse that takes as a parameter, among other things, a bitwise comparison of System.Globalization.NumberStyles . With this overload, you can specify what types of integer strings it can accept ( AllowExponent is one of them), so I would imagine, having not tested this that 9e09 would work. :)

Hope this helps!

A regex-based approach would look something like this:

Regex number = new Regex(@"-?\d+");
List<int> ints = number.Matches(raw)
                       .Cast<Match>()
                       .Select(m => Int32.Parse(m.Value))
                       .ToList();

However, this doesn't handle 9e09 if that's meant to represent 9 x 10 ^ 9 -- it will interpret it as two separate numbers, parsed as 9 and 9.

The "crazy" Linq way:

    private static IEnumerable<int> GetNumbers(string str)
    {
        foreach (var st in str.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries)
            .Where(s => (s.ToCharArray()
                .All(c => Char.IsDigit(c)))))
        {
            yield return Convert.ToInt32(st);
        }
    }

怎么样:

int[] xx = raw.Split( ' ' ).Where( ( s, o ) => Int32.TryParse( s, out o ) ).Select( p => Int32.Parse( p ) ).ToArray();

In response to itowlson, if somebody is concerned about an overflow, one can also use tryparse in this scenario with the aid of a temporary variable:

int tmp = 0;
var result = (from m in new Regex(@"-?\d+").Matches(s).OfType<Match>()
              let doesParse = int.TryParse(m.Value, out tmp)
              where doesParse
              select tmp).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM