Home   Cover Cover Cover Cover
 

Liste von Listen

ListOfLists.cs
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

//-----------------------------------------------------------------------
// This program reads a text of words and creates a list of lines.
// Every line is a list of words.
//-----------------------------------------------------------------------

class Test {
  
  // reads a word; returns an empty word at the end of a line
  static string ReadWord(StreamReader r) {
    int ch = r.Read();
    //--- skip non-letters
    while (ch >= 0 && ch != '\r' && !Char.IsLetter((char)ch)) ch = r.Read();
    //--- read and build word
    StringBuilder b = new StringBuilder();
    while (ch >= 0 && Char.IsLetter((char)ch)) {
      b.Append((char)ch);
      ch = r.Read();
    }
    return b.ToString();
  }
  
  // reads a line and returns a list of all words in this line
  static List<string> ReadLine(StreamReader r) {
    List<string> line = new List<string>();
    string word = ReadWord(r);
    while (word.Length > 0) {
      line.Add(word);
      word = ReadWord(r);
    }
    r.ReadLine();
    return line;
  }
  
  public static void Main(string[] args) {
    if (args.Length < 1) {
      Console.WriteLine("-- file name expected");
      return;
    }
    try {
      FileStream s = new FileStream(args[0], FileMode.Open);
      StreamReader r = new StreamReader(s);
      List< List<string>> list = new List< List<string>>();
      
      //--- read all lines in the text
      List<string> line = ReadLine(r);
      while (line.Count > 0) {
        list.Add(line);
        line = ReadLine(r);
      }
      s.Close();
      
      //--- print all lines and the words in them
      foreach (List<string> words in list) {
        foreach (string x in words) Console.Write(x + " ");
        Console.WriteLine();
      }
    } catch (FileNotFoundException) {
      Console.WriteLine("-- cannot open input file");
    }
  }
}