Advertisement
Hristo_B

CountContainedWords

Jul 26th, 2013
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4.  
  5. //Write a program that reads a list of words from a file words.txt
  6. //and finds how many times each of the words is contained in another file test.txt.
  7. //The result should be written in the file result.txt and
  8. //the words should be sorted by the number of their occurrences in descending order.
  9. //Handle all possible exceptions in your methods.
  10.  
  11. class CountContainedWords
  12. {
  13.     private static void CountWord(IDictionary<string,int> dictionary, string line)
  14.     {
  15.         string checkWord = "";
  16.         for (int i = 0; i < line.Length; i++)
  17.         {
  18.             while (line[i] != ' ' && line[i] != ',' && line[i] != '.')
  19.             {
  20.                 checkWord += line[i];
  21.                 i++;
  22.             }
  23.             foreach (string word in dictionary.Keys)
  24.             {
  25.                 if (checkWord == word)
  26.                 {
  27.                     dictionary[word]++;
  28.                     break;
  29.                 }
  30.             }
  31.             checkWord = "";
  32.         }
  33.     }
  34.  
  35.     static void Main(string[] args)
  36.     {
  37.         StreamReader text = new StreamReader(@"..\..\test.txt");
  38.         StreamReader words = new StreamReader(@"..\..\words.txt");
  39.         StreamWriter result = new StreamWriter(@"..\..\result.txt");
  40.  
  41.         IDictionary<string, int> dictionary = new SortedDictionary<string, int>();
  42.  
  43.         using (words)
  44.         {
  45.             string line;
  46.             while ((line = words.ReadLine()) != null)
  47.             {
  48.                 dictionary.Add(line, 0);
  49.             }
  50.         }
  51.  
  52.         using (text)
  53.         {
  54.             using (result)
  55.             {
  56.                 string line = words.ReadLine();
  57.                 while (line != null)
  58.                 {
  59.                     CountWord(dictionary, line);
  60.                     line = words.ReadLine();
  61.                 }
  62.                
  63.             }
  64.         }
  65.  
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement