c# - 如何在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);
谢谢您的帮助 !
解决方案
只有一个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);
推荐阅读
- python - 使用 Python 在图像上生成带有受控参数的文本
- php - 第二次从套接字写入和读取
- openmdao - 因子的含义正是在组中找到的单数/单数条目
- angular - 如何将日期字符串转换为时区特定日期。?
- sql-server - 为什么 sql server 更改跟踪似乎没有记录一些更改?
- python - TypeError:一元+的错误操作数类型:字符串创建中的'str'
- docker - nginx:在上游找不到 [emerg] 主机 - 忽略/停用而不是退出?
- mysql - 升级 open-ssh 后无法连接到任何数据库
- r - 回到 R 中循环的开头?
- python - 如何在python中的csv文件中写入网格