- using System;
- using System.IO;
- using System.Collections.Generic;
- namespace GiveMeFive
- {
- class MainClass
- {
- public static void Main (string[] args)
- {
- FileStream ftm = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Read);
- StreamReader sr = new StreamReader (ftm);
- List<List<string>> list = new List<List<string>> ();
- GiveMeFive (sr, list);
- }
- static void GiveMeFive(StreamReader sr,List<List<String>> list)
- {
- string str = null;
- if ((str = sr.ReadLine ()) == null) {
- if(list.Count==0)
- return;
- // when the files contain only 1,2,3 lines,
- if(list.Count<4)
- {
- for (int i = 0; i < list[0].Count; i++) {
- //when file has 3 lines, first element should not be processed.
- if(list[0].Count==3&&i==0)
- continue;
- if(list[0][i].Contains("xyz"))
- list[0].ForEach(Console.WriteLine);
- }
- }
- // 4,5 lines file: last 1 or last but one line match
- if(list.Count>3)
- {
- for (int i = 0; i < list.Count-2; i++) {
- // if there are 5 lists, the first elements should not be processed during disposing
- if(list.Count==5&&i==0)
- continue;
- if(list[i][2].Contains("xyz"))
- list[i].ForEach(Console.WriteLine);
- }
- }
- return;
- }
- // maintains 5 list contains 5,4,3,2,1 element(s) in each list
- if (list.Count < 5) {
- list.Add(new List<string>());
- }
- // append new element to lists and pop first element when the size is larger than 5,4,3,2,1 each.
- for (int i = 0; i < list.Count; i++) {
- list[i].Add(str);
- if(i+list[i].Count>5)
- list[i].RemoveAt(0);
- }
- //Cover first line and second line match case, and normal case that output five lines.
- if(list.Count>2 && list[0][list[0].Count-3].Contains("xyz"))
- list[0].ForEach(Console.WriteLine);
- GiveMeFive (sr, list);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1409201513676.html
来源: http://www.codesnippet.cn/detail/1409201513676.html