【问题标题】:How to get the last two occurrences of the same string in a text file C#如何在文本文件C#中获取最后两次出现的相同字符串
【发布时间】:2020-06-14 04:53:12
【问题描述】:

我有一个结构如下的文本文件:

Time: 5:31
.
.
Time: 5:50
.
.
Time: 6:30
.
.
Time: 7:30

为此,我试图获取“时间:”的最后两个实例,即:

Time: 6:30
.
.
Time: 7:30

我已经知道如何通过下面的代码获取最后一个实例:

string end_time = "";
string start_time = "";
string file = @"mypath.txt";

foreach(string line in File.ReadAllLines(file))
{
 end_time = Endtime_value(line, end_time);
 }
 Console.WriteLine(end_time);
 }

public static string Endtime_value(string line, string end_time)
{
   if (line.Contains("Time"))
   {
       end_time = line;
    }
            return end_time;
}

在上面我还可以返回文本文件的最后一行,因为它包含“时间:”的最后一个实例

但是,为此,我还尝试创建一个函数来返回“时间:”的倒数第二个实例,这将是 6:30,并且我并没有尝试以删除最后一行的方式执行此操作以及。

有没有办法以某种方式实现忽略文本文件最后一行的函数? (我文件的最后一行是“时间:”的最后一个实例)我打算这样做:

public static string Starttime_value(string line, string start_time,string file)
{
   //function here to ignore the last line of a text file
   //then apply the same logic of End_Time function to get second to the last instance of "Time: "     

}


【问题讨论】:

    标签: c# arrays string parsing


    【解决方案1】:

    您可以在遍历文件时简单地跟踪最后一个和倒数第二个时间条目:

    string last_time = "";
    string s_to_last_time = "";
    string file = @"mypath.txt";
    
    foreach(string line in File.ReadAllLines(file))
    {
        if (line.Contains("Time"))
        {
            s_to_last_time = last_time;
            last_time = line;
        }
    }
    
    Console.WriteLine("second to last instance: " + s_to_last_time);
    Console.WriteLine("last instance: " + last_time);
    

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多