{
static Dictionary<char, int> Counter(string file)
{
StreamReader sr = File.OpenText(file);
string words = sr.ReadToEnd();
sr.Close();
if (string.IsNullOrEmpty(words)) {
return null;
}
Dictionary<char, int> counter = new Dictionary<char, int>();
char last_char = '\0';? //存放遍歷中上壹個字符
foreach (char ch in words) {
//判斷上壹個字符是否是字母
if (!char.IsLetter(last_char)) {
//判斷當前字符是否是字母
if (char.IsLetter(ch)) {
//Console.Write(ch);
//轉換成大寫,也可以是小寫,不區分大小寫
char upper = Char.ToUpper(ch);
if (counter.ContainsKey(upper)) {
counter[upper]++;
} else {
counter.Add(upper, 1);
}
}
}
last_char = ch;
}
return counter;
}
static void Main(string[] args)
{
Dictionary<char, int> counter = Counter("test.txt");
//Console.WriteLine();
foreach (KeyValuePair<char, int> kv in counter) {
Console.WriteLine("{0}:{1}", kv.Key, kv.Value);
}
Console.ReadKey();
}
}