在文本文件中搜索一个单词,然后打印它存在的行

我想在文本文件中搜索特定关键字,比如 companyName。


程序将搜索单词,然后打印该单词所在的行,然后也会打印该单词下方的行。它应该对单词所在的每一行都这样做。IE 打印所有具有 companyName 的行及其下方的行。(理想情况下,这将写入 .txt 文件)


--->程序打印


公司名称:Tesco


地址:31, stern street(紧接下面的线路)


--编辑--


这是我现在正在工作的代码,供其他可能觉得有用的人使用:


static void Main(string[] args)

    {

        var sb = new StringBuilder();

        var lines = File.ReadAllLines(@"C:\file.txt");

        for (int i=0; i<lines.Length; i++)

        {

            var line = lines[i];

            if (line.IndexOf("companyName", StringComparison.CurrentCultureIgnoreCase) >= 0)

            {

                var nextLine = lines[i + 1];

                sb.AppendLine(line);

                sb.AppendLine(nextLine);

            }

        }


        File.WriteAllText(@"C:\out.txt", sb.ToString());

}


白衣染霜花
浏览 215回答 2
2回答

万千封印

您可以尝试在这些行中进行一些操作,其中变量 filePath 包含文件的路径,而 keyWord 包含您要查找的字符串:&nbsp; &nbsp; &nbsp; &nbsp; var keyWord = "companyName";&nbsp; &nbsp; &nbsp; &nbsp; var hasKeyword = false;&nbsp; &nbsp; &nbsp; &nbsp; foreach (var line in System.IO.File.ReadAllLines(filePath))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (line.Contains(keyWord))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasKeyword = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (hasKeyword)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasKeyword = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;

长风秋雁

也许像这样?using (var sr = new StreamReader(inFile))&nbsp; &nbsp;using (var sw = new StreamWriter(OutFile))&nbsp; &nbsp; &nbsp; while (!sr.EndOfStream)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var line1 = sr.ReadLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (line1.IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) >= 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sw.WriteLine(line1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sw.WriteLine(sr.ReadLine());&nbsp; &nbsp; &nbsp; }免责声明:未经测试,没有错误检查,我不对您使用此代码致残或以其他方式伤害的人负责
打开App,查看更多内容
随时随地看视频慕课网APP