0

到目前为止我有这个代码。它查看文本文档并显示其中包含单词word的行。我想让它跳过该行并在文本文档中显示下一个,我该怎么做?

例如,它看起来是文本文档,并在其中找到包含单词“word”的行,然后显示在它之后的行,没有其他行

string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
    if (line.Contains("word"))
    {
        Console.WriteLine(line);
    }

}

file.Close();
4

3 回答 3

1

如果您尝试在出现 in 一行后编写该word行,请尝试以下操作:

int counter = 0;
bool writeNextLine = false;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
    if (writeNextLine) 
    {
        Console.WriteLine(line); 
    }
    writeNextLine = line.Contains("word");    
    counter++;
}

file.Close();
于 2013-11-02T11:06:04.700 回答
1

像这样的东西将显示除空行和带有单词“word”的行之外的所有行

using (var rdr = new StreamReader(@"C:\Users\Gebruiker\Desktop\text.txt"))
{
     while (!(rdr.EndOfStream))
     {
         var line = rdr.ReadLine();
         if (!(line.Contains("word")) && (line != String.Empty))
         {
             Console.WriteLine(line);
         }
     }
}
Console.ReadKey();
于 2013-11-02T11:28:24.317 回答
0

这应该显示包含"word".

int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
    if (line.Contains("word"))
    {
        if ((line = file.ReadLine()) != null)
            Console.WriteLine(line);
    }
    counter++;
}
file.Close();
于 2013-11-02T11:03:33.377 回答