當前位置:成語大全網 - 新華字典 - c#問題,讀取某個txt文件,並統計字母個數

c#問題,讀取某個txt文件,並統計字母個數

class Program

{

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();

}

}