【问题标题】:How to traverse back and forth of text file line如何来回遍历文本文件行
【发布时间】:2014-04-10 17:16:39
【问题描述】:

我有一个文本文件,其中包含我需要处理的行。这是我的文本文件中存在的行的格式..

07 IVIN  15:37 06/03 022  00:00:14 600        2265507967       0:03   

08 ITRS  15:37 06/03 022  00:00:09 603        7878787887       0:03

08 ITRS  15:37 06/03 022  00:00:09 603        2265507967       0:03 

现在根据我的要求,我必须逐行读取此文本文件。现在,只要我将ITRS 输入任何行,我就必须在文本文件行的直接上方搜索数字2265507967 .一旦它在上行线中获得2265507967,它应该读取该行。 现在我正在将这些行读入字符串并根据空格分解成字符。这是我的代码..

var strings = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

我的问题是我没有办法遍历文本文件的顶部并搜索子字符串 .i.e. 2265507967.请帮忙。

【问题讨论】:

  • 只需保存上一行行的副本。
  • 不清楚您要达到的目标。但是,如果您需要查看当前行的上方或下方,最好将所有内容读入内存。最简单的是使用File.ReadAllLines,它返回所有行的string[]

标签: c# string char substring text-files


【解决方案1】:

我不知道在读取文件时能够后退(除了使用seek() 方法),但我可能错了......

更简单的方法是:

  1. 创建一个字典,键值是长数值,值是它所属的行:<2265507967,07 IVIN 15:37 06/03 022 00:00:14 600 2265507967 0:03>

  2. 逐行浏览文件,然后:

    一个。如果该行包含ITRS,则从该行获取值并检查您的字典。找到它后,清除字典并返回第 1 步。

    b.如果不包含ITRS,只需将数字和行添加为键值对即可。

这应该比一次通过一行更快,也更简单。缺点是它可能会占用大量内存。

编辑:我手边没有 .NET 编译器,所以我将提供一些伪代码来更好地解释我的答案:

//Initialization
Dictionary<string, string> previousLines = new Dictionary<string, string>();
TextReader tw = new TextReader(filePath);
string line = String.Empty;

//Read the file one line at a time
while((line = tw.ReadLine()) != null)
{
    if(line.contains("ITRS")
    {
        //Get the number you will use for searching
        string number = line.split(new char[]{' '})[4];
        //Use the dictionary to read a line you have previously read.
        string line = previousLines[number];

        previousLines.Clear(); //Remove the elements so that they do not interrupt the next searches. I am assuming that you want to search between lines which are found between ITRS tags. If you do not want this, simply omit this line.
        ... //Do your logic here.
    }
    else 
    {
         string number = line.split(new char[]{' '})[4];
         previousLines.Add(number, line);
    }
}

【讨论】:

  • 请你用语法说明一下..我无法得到它
  • 如果有 10000 行要添加到字典中,这会使我的过程变慢吗?
  • @Ram:我已经更新了我的答案。它应该能够处理这么多的字符串,但是我建议您对操作进行基准测试。
猜你喜欢
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多