如何在文本文件C#中获取同一字符串的最后两次出现

问题描述 投票:2回答:1

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

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

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

但是,为此,我还试图创建一个函数以返回“ 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: "     

}


    

我有一个文本文件,其结构如下:时间:5:31。 。时间:5:50。 。时间:6:30。 。时间:7:30为此,我试图获取“时间:”的最后两个实例,即:时间:6:30。 。 ...

c# arrays string parsing ignore
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.