前一段时间面试的时候,遇到一道面试题:求一段英文中的每个字母出现的次数。
今天我不求每个字母出现的频率,我求一段英文中每个单词出现的频率。
class="brush:csharp;gutter:true;">class Program
{
static void Main(string[] args)
{
string text = @"He was one of the best string instrument players in our town. He could not read music, but if he heard a tune a few times, he could play it";
Dictionary<string, int> wordfrequencies = CountWords(text);
foreach (KeyValuePair<string,int> entry in wordfrequencies)
{
Console.WriteLine("{0}:{1}",entry.Key,entry.Value);
}
Console.ReadKey();
}
static Dictionary<string,int> CountWords(string text)
{
//创建单词到频率的新映射
Dictionary<string, int> wordfrequencies = new Dictionary<string, int>();
//将文本分解成单词
string[] words = Regex.Split(text, @"\W+");
//添加或更新映射
foreach (string word in words)
{
if (wordfrequencies.ContainsKey(word))
{
wordfrequencies[word]++;
}
else
{
wordfrequencies[word] = 1;
}
}
return wordfrequencies;
}
}