static void Main(string[] args) { StreamReader reader = new StreamReader("../../file.txt"); string text = reader.ReadToEnd(); string[] splitedText = text.Split(new char[] { ' ', ',', '.', ';' }, StringSplitOptions.RemoveEmptyEntries); Trie trie = TrieFactory.GetTrie() as Trie; foreach (var word in splitedText) { trie.AddWord(word); } var words = trie.GetWords(); StringBuilder sb = new StringBuilder(); foreach (var word in words) { sb.AppendLine(word + " -> " + trie.WordCount(word)); } Console.WriteLine(sb); }
/// <summary> /// Recursive method to add word. Gets the first char of the word, /// creates the child TrieNode if null, and recurses with the first /// char removed from the word. If the word length is 0, return. /// </summary> private void AddWord(TrieNode trieNode, char[] word) { if (word.Length == 0) { trieNode.IsWord = true; trieNode.WordCount++; } else { var c = Utilities.FirstChar(word); TrieNode child; trieNode.Children.TryGetValue(c, out child); if (child == null) { child = TrieFactory.GetTrieNode(c); trieNode.Children[c] = child; } var cRemoved = Utilities.FirstCharRemoved(word); AddWord(child, cRemoved); } }