我正在尝试计算给定单词的字母。我卡在最后。我不知道如何计算这些字母。
static void Main(string[] args)
{
Console.WriteLine("Enter a word:");
string kelime = Console.ReadLine();
int numberofLetters = kelime.Length;
Console.WriteLine("Your word has {0} characters", numberofLetters);
for (int i = 0; i < numberofLetters; i++)
{
if
}
}
答案 0 :(得分:1)
您应该存储已处理的字母以及处理它们的次数。一个很好的选择,它将是一个字典,键入字母和值,你发现这封信的时间。
var lettersDictionary = new Dictionary<char, int>();
for (int i = 0; i < numberofLetters; i++)
{
var currentLetter = kelime[i];
if(lettersDictionary.ContainsKey(currentLetter))
{
// The dictionary contains the currentLetter.
// So we increase the times we found it by 1.
lettersDictionary[currentLetter] += 1;
}
else
{
// The dictionary doesn't contain the currentLetter.
// So we add the new key with the value of 1.
lettersDictionary.Add(currentLetter,1);
}
}
完成上述操作后,您可以构建所需的输出,如下所示:
var keyValues = lettersDictionary.Keys.Select(key=>$"{key}: {lettersDictionary[key]}");
var output = string.Join(",", keyValues);