Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

}


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...