将字符串转换为整数数组

本文关键字:整数 数组 转换 字符串 | 更新日期: 2023-09-27 17:59:57

这是我有 3 个整数的字符串,我想将其存储在 3 个整数变量中,但我找不到答案。

string orders = "Total orders are 2222 open orders are 1233 closed are 222";

这就是我想做的。

int total = 2222;
int close = 222;
int open = 1233;

将字符串转换为整数数组

尝试使用正则表达式(提取模式(和 Linq(将它们组织成int[](:

  string orders = "Total orders are 2222 open orders are 1233 closed are 222";
  int[] result = Regex
    .Matches(orders, "[0-9]+")
    .OfType<Match>()
    .Select(match => int.Parse(match.Value))
    .ToArray();

你可以只使用 Linq 来做到这一点:

int[] result =  orders
  .Split(' ')
  .Where(s => s
     .ToCharArray()
     .All(c => Char.IsDigit(c)))
  .Select(s => Int32.Parse(s))
  .ToArray();

这是一种方式

namespace StringToIntConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string orders = "Total orders are 2222 open orders are 1233 closed are 222";
            string[] arr = orders.Split(' ');
            List<int> integerList = new List<int>();
            foreach(string aString in arr.AsEnumerable())
            {
                int correctedValue ;
                if(int.TryParse(aString,out correctedValue))
                {
                    integerList.Add(correctedValue);
                }
            }
            foreach (int aValue in integerList)
            {
                Console.WriteLine(aValue);
            }
            Console.Read();
        }
    }
}

我会这样做:

var intArr = 
    orders.Split(new[] { ' ' }, StringSplitOptions.None)
          .Select(q =>
                  {
                      int res;
                      if (!Int32.TryParse(q, out res))
                          return (int?)null;
                      return res;
                  }).Where(q => q.HasValue).ToArray();

这将从字符串中提取整数:

var numbers =
    Regex.Split(orders, @"'D+")
        .Where(x => x != string.Empty)
        .Select(int.Parse).ToArray();

输出

numbers[0] == 2222
numbers[1] == 1233
numbers[2] == 222

您可以依次检查每个字符,看看它是否是数值:

string orders = "Total orders are 2222 open orders are 1233 closed are 222";
List<int> nums = new List<int>();
StringBuilder sb = new StringBuilder();
foreach (Char c in orders)
{
    if (Char.IsDigit(c))
    {
        //append to the stringbuilder if we find a numeric char
        sb.Append(c);
    }
    else
    {
        if (sb.Length > 0)
        {
            nums.Add(Convert.ToInt32(sb.ToString()));
            sb = new StringBuilder();
        }
    }
}
if (sb.Length > 0)
{
    nums.Add(Convert.ToInt32(sb.ToString()));
}
//nums now contains a list of the integers in the string
foreach (int num in nums)
{
    Debug.WriteLine(num);
}

输出:

2222
1233
222
int[] results =  orders.Split(' ').Where(s => s.ToCharArray().All(c => Char.IsDigit(c)))
    .Select(s => Int32.Parse(s)).ToArray();