C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: We use the new char syntax and initialize the array size to char.MaxValue, which is a constant value defined in the .NET Framework.
CharPart 2: We read in the file where we are counting letters. The File.ReadAllText method efficiently reads the file and places its contents into a string.
File.ReadAllTextNext: We add up frequencies by iterating over each letter, and casting it to an int. We increment each "slot" for the letters we find.
Finally: We display all letter or digit characters we found. The Console.WriteLine statement actually prints the results to the screen.
ConsoleC# program that counts frequency of letters
using System;
using System.IO;
class Program
{
static void Main()
{
// 1.
// Array to store frequencies.
int[] c = new int[(int)char.MaxValue];
// 2.
// Read entire text file.
string s = File.ReadAllText("text.txt");
// 3.
// Iterate over each character.
foreach (char t in s)
{
// Increment table.
c[(int)t]++;
}
// 4.
// Write all letters found.
for (int i = 0; i < (int)char.MaxValue; i++)
{
if (c[i] > 0 &&
char.IsLetterOrDigit((char)i))
{
Console.WriteLine("Letter: {0} Frequency: {1}",
(char)i,
c[i]);
}
}
}
}
Input file
aaaa
bbbbb
aaaa
bbbbb
aaaa bbbbb
CCcc
xx
y y y y y
Z
Output
Letter: C Frequency: 2
Letter: Z Frequency: 1
Letter: a Frequency: 12
Letter: b Frequency: 15
Letter: c Frequency: 2
Letter: x Frequency: 2
Letter: y Frequency: 5
Review: Most important in the solution is how the array is declared and the constants are used.