【问题标题】:C# Extracting Ints from String and Comparing [closed]C# 从字符串中提取整数并进行比较 [关闭]
【发布时间】:2023-03-20 10:54:01
【问题描述】:

例如,我有几场体育比赛的一串结果,每支球队都用一个字母表示。我想专注于“A”队,并将其得分与其他球队进行比较,以打印出 A 队赢了、输了、平了多少场比赛等......下面显示的示例字符串。

string results = " A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9";

我认为最好的方法是提取 A 队的所有分数并用它们填充一个数组,并对剩余的分数执行相同的操作。我已经尝试使用 index 来解决这个问题,但一直被难住了。有什么想法吗?

编辑:由于未发布尝试:

char[] tobeconverted = results.Where(Char.IsDigit).ToArray();
        int[] sequence = new int[10];

        for (int i = 0; i < tobeconverted.Length; i++)
        {
            sequence[i] = Convert.ToInt32(tobeconverted[i].ToString());

        }

这会用所有数字填充数组,所以我不确定如何区分它们。

        string teamA = "A ";
        int indexOfNextOccurance = results.IndexOf(teamA, results.IndexOf(teamA) + 1);

然后我计划使用带有子字符串的索引来提取数字并转换为 int,但这仅适用于第一次和第二次出现,我不知道如何获取其他数字值。

【问题讨论】:

  • 当您要求社区解决您无法解决的问题时,最好发布您的尝试,以便我们看到这不是 give me teh codez i> 类型的问题
  • 此外,发布您的尝试会阻止我们建议您已经尝试过并丢弃的不可行的东西。
  • 8条数据是如何粘在一个字符串中的?
  • @Plutonix -- 可能保存到文本文件,打印在纸上,扫描回来,然后 OCRed,我猜。
  • 现在你有两个问题。

标签: c# compare


【解决方案1】:
  1. 在逗号处分割字符串。这将返回一个字符串数组。
  2. 用空格分割数组中的每个字符串。这会产生另一个数组。
  3. 提取数组的成员。

这是一个示例程序。

  class Program
  {
    static void Main(string[] args)
    {

      string results = " A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9";

      string[] matches = results.Trim().Split(',');

      List<Match> sportResults = new List<Match>();
      foreach (string match in matches)
      {
        string[] parts = match.Trim().Split(null);

        sportResults.Add(new Match() {
          Team1 = parts[0], Score1 = int.Parse(parts[1]),
          Team2 = parts[2], Score2 = int.Parse(parts[3])});

      }

      sportResults.ForEach(a => Console.WriteLine(a));
    }
  }

将团队/分数封装在一个单独的类中。

class Match
  {
    public string Team1 { get; set; }
    public string Team2 { get; set; }

    public int Score1 { get; set; }
    public int Score2 { get; set; }

    public override string ToString()
    {
      return "Team " + Team1 + " " + Score1 + " VS " + Team2 + " " + Score2;
    }
  }

【讨论】:

  • 谢谢,不胜感激
【解决方案2】:
string results = "A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9";
        List<int> teamAScores = new List<int>();
        List<int> otherTeamScores = new List<int>();
        foreach(string scoreSet in results.Split(','))
        {
            scoreSet.Replace(" ", "");
            int teamA = -1;
            int teamX = -1;
            int.TryParse(scoreSet.Substring(1, 1), out teamA);
            int.TryParse(scoreSet.Substring(3, 1), out teamX);
            if (teamA > -1 && teamX > -1)
            {
                teamAScores.Add(teamA);
                otherTeamScores.Add(teamX);
            }
        }

您现在有一个列表,其中每场比赛的得分在索引方面匹配。

【讨论】:

  • 别担心——保重!
猜你喜欢
  • 2016-09-16
  • 1970-01-01
  • 2017-08-13
  • 2014-12-14
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2018-09-11
相关资源
最近更新 更多