Advertisement
Guest User

Untitled

a guest
Mar 5th, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _03.WordsOccurences
  7. {
  8. class WordsOcc
  9. {
  10. static void CountWords(string[] words)
  11. {
  12. Dictionary<string, int> table = new Dictionary<string, int>();
  13. for (int i = 0; i < words.Length; i++)
  14. {
  15. if (!table.ContainsKey(words[i]))
  16. {
  17. table.Add(words[i], 1);
  18. }
  19. else
  20. {
  21. int value = 0;
  22. table.TryGetValue(words[i], out value);
  23. value++;
  24. table[words[i]] = value;
  25. }
  26. }
  27.  
  28. List<KeyValue> list = new List<KeyValue>();
  29.  
  30. foreach (var item in table)
  31. {
  32. KeyValue kv = new KeyValue();
  33. kv.Count = item.Value;
  34. kv.Word = item.Key;
  35. list.Add(kv);
  36. }
  37.  
  38. list.Sort();
  39.  
  40. foreach (var item in list)
  41. {
  42. Console.WriteLine("{0} --> {1}",item.Word, item.Count );
  43. }
  44. }
  45. class KeyValue : IComparable
  46. {
  47. public int Count { get; set; }
  48. public string Word { get; set; }
  49.  
  50.  
  51. public int CompareTo(object obj)
  52. {
  53. KeyValue kv = obj as KeyValue;
  54. return this.Count.CompareTo(kv.Count);
  55. }
  56. }
  57. static void Main(string[] args)
  58. {
  59. string str = "This is the TEXT. Text, text, text – THIS TEXT! Is this the text?";
  60. str = str.ToLower();
  61. char[] delimiters = { ' ', '-', '–', '?', '!', ',', '.' };
  62. string[] words = str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
  63. CountWords(words);
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement