1 Public classWords2 {3 Public Staticdictionary<string,int> CountWords (stringtext)4 {5dictionary<string,int> Frequencies;//Create a new map from Word to frequency6frequencies =Newdictionary<string,int>();7 string[] Words = regex.split (text,@"\w+");//break the text into words8 //Add or follow a new map9 foreach(varWordinchwords)Ten { One if(frequencies. ContainsKey (word)) A { -frequencies[word]++; - } the Else - { -Frequencies[word] =1; - } + } - returnfrequencies; + } A}
Print
1 Static voidMain (string[] args)2 {3 stringText ="president Xi Jinping have asked the armed forces to clear up the bad influence left by the graft case of Xu Caihou, a F Ormer senior commander.";4dictionary<string,int> frequencies =words.countwords (text);5 foreach(keyvaluepair<string,int> Entryinchfrequencies)6 {7 stringWord =entry. Key;8 intfrequency =entry. Value;9Console.WriteLine ("{0}:{1}", Word, frequency);Ten } One Console.readkey (); A}
In-depth comprehension of C # code snippets-using Dictionary<tkey,tvalue> to count words in text