c#问题,读取某个txt文件,并统计字母个数

读取一个txt文件(内容为英文),取每个单词的首字母,统计这些字母的个数(例如:a:23个,b:22个……z:2个),不分大小写,貌似要用到index(),在线等,好的追加!!thank you!!

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


温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-19
用linq就可以。
private string StatisticsLetters(string text)
{
StringBuilder sb = new StringBuilder();
string s = text;
var statistics =
from c in s
group c by c into g
select new { g.Key, count = g.Count() };
var mostFrequestFirst =
from entry in statistics
orderby entry.count descending
select entry;
foreach (var entry in mostFrequestFirst)
{
sb.AppendFormat("{0}:{1}{2}", entry.Key, entry.count, System.Environment.NewLine);
}
return sb.ToString();
}本回答被网友采纳
第2个回答  2013-05-19

主函数FileWordStatistics

输入:文件路径

输出:一个以字母为键,以统计的词汇个数为值的字典。
public Dictionary<char, int> FileWordStatistics(string path)
{
    Dictionary<char,int> result=new Dictionary<char,int>();
    using (StreamReader reader = new StreamReader(path))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            string[] words = line.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries);
            foreach (string word in words)
            {
                if (word[0] >= 'a' && word[0] <= 'z')
                    AddCount(result, word[0]);
            }
        }
    }
    return result;
}
private void AddCount(Dictionary<char, int> dictionary, char firstChar)
{
    if (dictionary.ContainsKey(firstChar))
        dictionary[firstChar]++;
    else
        dictionary.Add(firstChar, 1);
}

相似回答