I need to write a script that counts how many times each letter occurs in a given text. I was successful at making it work, and although I'm sure that there's a better way to do it, the script does what it's supposed to do:
static void Main(string[] args)
{
string text;
Dictionary<char, int> letterCount = new Dictionary<char, int>();
List<char> nonLetters = new List<char>
{
'.', '!', ',', '?', ':', ';', '#', '@', '$', '&', '(',')', '-',
'+', '=', '\"','\'', ' ', '\n', '1', '2', '3', '4', '5', '6',
'7', '8','9', '0'
};
Console.WriteLine("Enter your text");
text = Console.ReadLine();
text = text.ToLower();
for(int i = 0; i < text.Length; i++)
{
if (!letterCount.ContainsKey(text[i]))
{
if (!nonLetters.Contains(text[i]))
{
letterCount.Add(text[i], 1);
}
}
else
{
letterCount[text[i]] += 1;
}
}
foreach (KeyValuePair<char, int> kvp in letterCount)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
Console.ReadKey();
}
My first attempt wasn't successful, though. And I don't understand why and what the difference is. This is what the for-loop in my initial code looked like:
for(int i = 0; i < text.Length; i++)
{
if (!letterCount.ContainsKey(text[i]) && !nonLetters.Contains(text[i]))
{
letterCount.Add(text[i], 1);
}
else
{
letterCount[text[i]] += 1;
}
}
This is what the Exception message says: System.Collections.Generic.KeyNotFoundException "The given key'(' was not present in the dictionary
Please, help me understand why using the "&&" operator doesn't work while the embedded if-statement with the same condition does.