我想从字符串中搜索整数并将它们存储在数组中

本文关键字:存储 数组 整数 字符串 搜索 | 更新日期: 2023-09-27 17:56:11

我正在构建一个基于控制台的彩票游戏,用户可以在其中输入他/她选择的数字。我需要检查数字是否在 1-39 之间,并且用户输入了正好 7 个有效数字。我想以一种用户在控制台中的一行字符串中写入它们的方式执行此操作,并且程序会找到任何空格、逗号或其他非数字字符并忽略它们。其余的彩票号码应存储在不包含任何重复项的整数数组中。

我当前的版本非常可怕,因为如果用户写入例如数字之间的 2 个空格,它很容易出错。

Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
        string userRow = Console.ReadLine();
        int[] userLottery = new int[7];
        for(int i = 0; i < userLottery.Length; i++)
            {
                userLottery = userRow.Split(',', '.', ' ').Select(x => int.Parse(x)).ToArray();
                if(userLottery[i] > 7)
                {
                    Array.Resize(ref userLottery, 7);
                }
            }

我想以更方便的方式替换我当前的方式,其中用户错误量不会影响程序。如果用户写入多个空格,则会发生错误。

我试图构建正则表达式来处理这些情况,但我不能使用它将它们存储在数组中。

string userChoice = Console.ReadLine();
        MatchCollection userNumbers = Regex.Matches(userChoice, @"'d+");
        int[] userRow;
        for(int i = 0; i < userNumbers.Count; i++)
        {
            userRow[i] = userNumbers[i].Value;
        }

也就是说字符串不能转换为 int[]...

我想从字符串中搜索整数并将它们存储在数组中

您可以使用带有RemoveEmptyEntriesint.tryParseString.Split来使用此 LINQ 查询:

int num = 0;
int[] userLottery = userRow.Trim()
    .Split(new[] { '.', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Where(s => int.TryParse(s.Trim(), out num) && num > 0 && num < 40)
    .Select(s => num)
    .Distinct()
    .ToArray();
if(userLottery.Length != 7)
    Console.WriteLine("Enter 7 valid numbers between 1 and 39");
else
    Console.WriteLine("You have chosen following numbers: " + string.Join(",", userLottery));

Enumerable.Distinct根据请求删除重复项。

您的代码与用户的指令不匹配。以下内容执行您告诉用户的操作:

  Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
  int[] userLottery = new int[7];
  int i = 0;
  while (i < 7)
  {
      Console.Write("Your choice #{0}: ", i+1);
      string userRow = Console.ReadLine();
      int userNumber;
      if (!Int32.TryParse(userRow, out userNumber) || userNumber < 1 || userNumber > 39)
      {
          Console.WriteLine("Invalid number! Please try again!");
      }
      else
      {
          userLottery[i++] = userNumber;
      }
  }
为此

使用Regex.Split()来处理多个空格。

string[] numbers = Regex.Split(userRow, @"'s+");

's+表示一个或多个空格。如果需要,您只能将[ ]+用于空间。

您可以先使用正则表达式解析它,然后它应该可以工作。

  using System.Text.RegularExpressions;
  Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
  string userRow = Console.ReadLine();
  int[] userLottery = new int[7];
  string[] userEnter = Regex.Split(userRow, " ");
  int n = 0;
  int k = 0;
  for (int i = 0; i < userEnter.Length; i++)
  {
    bool isNumeric = int.TryParse(userEnter[i], out n);
    if(isNumeric == true)
    {
      userLottery[k] = int.Parse(userEnter[i]);
      k++;
    }
  }

使用以下代码

        Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");
        string data = Console.ReadLine();
        int[] userLottery = new int[7];
        int i = 0;
        StringBuilder num = new StringBuilder();
        foreach (char item in data)
        {

            if (!Char.IsDigit(item))
            {
                if (num.Length == 0)
                    continue;
                userLottery[i] = int.Parse(num.ToString());
                i++;
                num.Clear();
                continue;
            }
            num.Append(item);
        }
        if(num.Length > 0)
            userLottery[i] = int.Parse(num.ToString());