【问题标题】:How to find the maximum number of same chars in a row inside an array in C#如何在C#中的数组内的一行中找到最大相同字符数
【发布时间】:2021-01-06 06:48:49
【问题描述】:

(试图为我的问题寻找较早的答案,但没有找到任何答案......)

假设我有一个这样的数组:

string[] chars = {"1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x"};

我需要找到方法来提取数组中一行中“x”的最大数量, 所以在这个例子中,我总共有 10 个“x”,但连续只有 5 个, 所以我需要提取数字 5。

试过这个方法...但是它当然不能与第一个字符(i-1)一起工作。

  string[] chars = { "1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x" };
        int count = 0;
        for (int i=0; i < chars.Length; i++)
        {

            if ((chars[i] == "x") && (chars[i] == chars[i - 1])) ;
     
                count++;
        }
        Console.WriteLine(count);

感谢您的帮助!

【问题讨论】:

  • 对分组项目使用 LINQ 的 GroupByOrderByDescendingCount,并使用 First(如果列表可以为空,则使用 FirstOrDefault)。
  • 是的,我尝试使用 for 循环来计算 "x" 的字符数,如果下一个字符与最后一个字符不同则停止,但它会在序列之前停止计数。
  • 您想提供无效的代码吗?通过这种方式,我们可以为您提供更有建设性的反馈,而不是用勺子喂您答案。
  • “最佳方式” 以意见为准 使得这个问题对于 SO 来说可能是题外话

标签: c# arrays charsequence


【解决方案1】:

只有 foreach 和迭代器方法的低技术通用方法

给定

public static IEnumerable<(T item, int count)> GetStuff<T>(IEnumerable<T> source)
{
   T current = default;
   var started = false;
   var count = 0;
   foreach (var item in source)
   {
      if (!EqualityComparer<T>.Default.Equals(item,current) && started)
      {
         yield return (current, count);
         count = 0;
      }
      current = item;
      count++;
      started = true;
   }
   yield return (current, count);
}

用法

string[] chars = {"1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x"};

var results = GetStuff(chars);

foreach (var result in results)
   Console.WriteLine(result);

结果

(1, 1)
(x, 1)
(1, 1)
(x, 5)
(1, 3)
(x, 1)
(1, 1)
(x, 3)

如果你想要最大的东西

var results = GetStuff(chars)
    .Where(x => x.Item == "x")
    .Max(x => x.Count);

【讨论】:

  • 当输入为string[] chars = { "1", null, "x", "x"};时会得到(x, 3)
  • @MichaelMao 是的:/,已更新以修复 null 并使其完全通用
猜你喜欢
  • 2022-11-18
  • 2016-03-27
  • 2011-04-17
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2022-11-01
相关资源
最近更新 更多