byte count = 0;
string word = "muumuu";
string res= word;
bool flg = true;
foreach(char ch in word)
{
res = res.Remove(0,1);
if(res.Contains(ch))
{
flg = false;
count ;
Console.WriteLine($"there are {count} same chars : {ch}");
}
}
if(flg)
{
Console.WriteLine($"All chars are different in : {word} ");
}
輸出是:
有 1 個相同的字符:m
有 2 個相同的字符:您
有 3 個相同的字符:您
有 4 個相同的字符:您
問題是如何計算相同的字符,例如:
有 2 個相同的字符:m
有 4 個相同的字符:u
uj5u.com熱心網友回復:
您必須將計數與結果的輸出分開。
以下解決方案收集字典中的字符數,然后顯示字典的內容:
string word = "muumuu";
var counts = new Dictionary<char, int>();
foreach (var ch in word)
{
if (counts.ContainsKey(ch))
counts[ch] ;
else
counts[ch] = 1;
}
foreach (var chCount in counts)
{
Console.WriteLine($"{chCount.Value} occurrences of '{chCount.Key}'");
}
使用Linq GroupBy方法的非常緊湊的替代解決方案:
string word = "muumuu";
foreach (var group in word.GroupBy(c => c))
{
Console.WriteLine($"{group.Count()} occurrences of '{group.Key}'");
}
GroupBy 對單詞中的字符進行分組,以便每個不同的字符創建一個組,每個組包含收集到的相同字符。然后可以使用Count 對這些進行計數。
結果:
2 occurrences of 'm'
4 occurrences of 'u'
uj5u.com熱心網友回復:
Klaus 的回答可能更容易理解,但您也可以使用此功能,它的作用大致相同:
public static int CountDuplicates(string str) =>
(from c in str.ToLower()
group c by c
into grp
where grp.Count() > 1
select grp.Key).Count();
用法: var dupes = $"{word} - Duplicates: {CountDuplicates(word)}";
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/389756.html
