【发布时间】: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: "
}
【问题讨论】: