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