How to get the last two occurrences of the same string in a text file C#

懵懂的女人 提交于 2020-06-27 13:03:11

问题


I have a text file structured like this:

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

For this, I am trying to obtain the last two instances of "Time: ", which would be:

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

I already know how to obtain the last instance, by way of my code below:

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;
}

In the above I could also return the last line of the text file, as it contains the last instance of "Time: "

However, for this, I am also trying to create a function to return the second to last instance of "Time: " which would be 6:30 and am not trying to do it in a way where it deletes the last line as well.

Is there a way to somehow implement a function to ignore the last line of a text file? (my last line of the file is the last instance of "Time: ") I was planning on doing it as so:

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: "     

}



回答1:


You may simply keep track of the last, and second-to-last, time entry, as you iterate over the file:

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);


来源:https://stackoverflow.com/questions/62368471/how-to-get-the-last-two-occurrences-of-the-same-string-in-a-text-file-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!