C# 練習題 (12)

C# 練習題 (12)

練習題 (12): Extract uppercase words from a file, extract unique words.

本題可以利用 Regex 類別擷取檔案中所有的單字,並將單字放進 .NET 的泛型 Hash Table:Dictionary 類別中計算單字與其出現次數。

測試檔案內容:

In this file, THERE ARE some UPPERCASE words.

And, There ARE some redundant WORDS IN the content:

foo bar foo CSHARP Dictionary CSHARP Firefox Opera IE

JUST FOR FUN.

程式碼:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. namespace DictionaryTest
  6. {
  7. internal class Program
  8. {
  9. private static void Main( string [ ] args)
  10. {
  11. StreamReader sr = new StreamReader( "in.txt" );
  12. Dictionary<string, int> d = new Dictionary<string, int>( );
  13. while (sr.Peek ( ) != -1 )
  14. {
  15. string s = sr.ReadToEnd ( );
  16. Regex r = new Regex( @"(\w+)", RegexOptions.IgnoreCase );
  17. Match m = r.Match (s);
  18. while (m.Success )
  19. {
  20. Group g = m.Groups [ 1 ];
  21. if (!d.ContainsKey (g.ToString ( ) ) )
  22. {
  23. d.Add (g.ToString ( ), 1 );
  24. }
  25. else
  26. {
  27. d[g.ToString ( ) ] += 1;
  28. }
  29. m = m.NextMatch ( );
  30. }
  31. }
  32. Console.WriteLine ( "Uppercase words:" );
  33. Dictionary<string, int>.KeyCollection kc = d.Keys;
  34. foreach ( string s in kc)
  35. {
  36. if (Regex.IsMatch (s, @"^[A-Z]+$" ) )
  37. {
  38. Console.WriteLine (s);
  39. }
  40. }
  41. Console.WriteLine ( "Unique words:" );
  42. foreach (KeyValuePair<string, int> kvp in d)
  43. {
  44. if (kvp.Value == 1 )
  45. {
  46. Console.WriteLine (kvp.Key );
  47. }
  48. }
  49. sr.Dispose ( );
  50. }
  51. }
  52. }