首页 > 解决方案 > 如何在C#中的数组内的一行中找到最大相同字符数

问题描述

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

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

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);

谢谢您的帮助 !

标签: c#arrayscharsequence

解决方案


只有一个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);

推荐阅读