C# 如何在C中查找数组中一行中相同字符的最大数目#
(试图寻找我问题的早期答案,但没有找到任何…) 假设我有这样一个数组:C# 如何在C中查找数组中一行中相同字符的最大数目#,c#,arrays,charsequence,C#,Arrays,Charsequence,(试图寻找我问题的早期答案,但没有找到任何…) 假设我有这样一个数组: string[] chars = {"1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", &
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”、“x”、“1”、“1”、“1”、“x”、“x”、“x”、“x”};
整数计数=0;
for(int i=0;i
谢谢你的帮助 只有一个
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);
}
结果
(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);
对分组项使用LINQ的
GroupBy
,OrderByDescending
,Count
和First
(或FirstOrDefault
,如果列表可以为空)。是的,我尝试了for循环,该循环对“x”的字符进行计数,如果下一个字符与上一个字符不同,则停止,但它在序列之前停止计数。是否提供不起作用的代码?通过这种方式,我们可以给你更具建设性的反馈,而不是填鸭式地给你答案。@KunalMukherjee和“best way”取决于意见,因此当输入为string[]chars={“1”,null,“x”,“x”}时,这个问题可能会偏离主题
将获得(x,3)
@MichaelMao yeah:/,更新为修复null并使其完全通用
(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);