Home   Cover Cover Cover Cover
 

Häufigkeitszählung von Wörtern

A09.cs
using System;
using System.Collections;
using System.IO;
using System.Text;

// Reads a text of words and prints them in sorted order 
// together with their frequencies.
class WordCount {
  
  static void Main(string[] arg) {
    SortedList list = new SortedList();
    StreamReader r = File.OpenText(arg[0]);
    int ch = r.Read();
    while (ch >= 0) {
      //--- search start of word
      while (ch >= 0 && !Char.IsLetter((char)ch)) ch = r.Read();
      //--- build word
      StringBuilder b = new StringBuilder();
      while (ch >= 0 && Char.IsLetterOrDigit((char)ch)) {
        b.Append((char)ch);
        ch = r.Read();
      }
      //--- enter word
      if (b.Length > 0) {
        string word = b.ToString();
        if (list.Contains(word))
          list[word] = (int)list[word] + 1;
        else
          list[word] = 1;
      }
    }
    foreach (string word in list.Keys)
      Console.WriteLine("{0}: {1}", word, list[word]);
    r.Close();
  }
}