从文本文件中读取并写入另一个文本文件

时间:2014-02-18 18:16:55

标签: c#

我在记事本中的数据看起来像这样 我正在把它写到输出文件

01 some Data
02 some Data
02 some data
03 some data(End of client 1)
01 some data 
02 some data
02 some data
02 some data
03 some data(End of client 2)

我想计算值02出现的次数,并在每个客户端结束后显示它。

我正在使用这段代码来计算

int count = File.ReadLines(@"C:\Exercises\gamenam.dat").Count(
               line => line.StartsWith("02")
               );

我想知道在每个客户结束后如何在03之后显示它?

2 个答案:

答案 0 :(得分:0)

使用循环和正则表达式可能更容易:

int count = 0;
foreach (string line in File.ReadLines(@"C:\Exercises\gamenam.dat"))
{
    if (line.StartsWith("02"))
        count++;

    Match clientMatch = Regex.Match(line, @"(?<=\(End of client )\d+(?=\))");
    if (clientMatch.Success)
    {
        // Replace line below with write to output file
        Console.WriteLine("Client {0} has {1} occurrences of \"02\".", 
                          clientMatch.Value, count);
        count = 0;
    }
}

答案 1 :(得分:0)

最好用循环完成。请参阅下面的代码示例:

            System.IO.StreamReader File = new System.IO.StreamReader(@"C:\Exercises\gamenam.dat");
        System.IO.StreamWriter File2 = new System.IO.StreamWriter(@"C:\Exercises\gamenam_result.dat");

        string line;
        int count = 0;

        while ((line = File.ReadLine()) != null)
        {
            if (line.StartsWith("02"))
                count++;
            if (line.Contains("End of client"))
            {
                File2.Write(count.ToString() + "\n");
                count = 0;
            }
        }

        File.Close();
        File2.Close();

您可以随意格式化它......