之前我问过这个问题,但是大多数人都不理解我的问题。
我有两个文本文件。 Gamenam.txt
这是我正在阅读的文本文件,以及gam enam_2.txt
。
在gamenam.txt
我有这样的字符串:
01456
02456
05215
05111
01421
03117
05771
01542
04331
05231
我写了一段代码to count number of times substring "05" appears in text file before substring "01"
。
写入gamenam_1.txt
的输出是:
01456
02456
05215
05111
2
01421
03117
05771
1
01542
04331
05231
1
这是我为实现
而编写的代码string line;
int counter = 0;
Boolean isFirstLine = true;
try
{
StreamReader sr = new StreamReader("C:\\Files\\gamenam.txt");
StreamWriter sw = new StreamWriter("C:\\Files\\gamenam_1.txt");
while ((line = sr.ReadLine()) != null)
{
if (line.Substring(0, 2) == "01")
{
if (!isFirstLine)
{
sw.WriteLine(counter.ToString());
counter = 0;
}
}
if (line.Substring(0, 2) == "05")
{
counter++;
}
sw.WriteLine(line);
if (sr.Peek() < 0)
{
sw.Write(counter.ToString());
}
isFirstLine = false;
}
sr.Close();
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Exception finally block.");
}
该代码运作正常。
现在我必须在编写行 之前编写代码 来打印子串“05”的计数。
我的输出应该是这样的:
2
01456
02456
05215
05111
1
01421
03117
05771
1
01542
04331
05231
显然我应该首先将行写入临时字符串数组,计数然后写入计数,然后再写入临时数组中的行。
我是开发新手,所以我一直想弄清楚我是如何实现这一目标的。
任何帮助都将受到高度赞赏。
答案 0 :(得分:2)
试试这个
string line;
int counter = 0;
Boolean isFirstLine = true;
try
{
StreamReader sr = new StreamReader("C:\\Files\\gamenam.txt");
StreamWriter sw = new StreamWriter("C:\\Files\\gamenam_1.txt");
var lines = new List<string>(); //Here goes the temp lines
while ((line = sr.ReadLine()) != null)
{
if (line.Substring(0, 2) == "01")
{
if (!isFirstLine)
{
sw.WriteLine(counter.ToString()); //write the number before the lines
foreach(var l in lines)
sw.WriteLine(l); //actually write the lines
counter = 0;
lines.Clear(); //clear the list for next round
}
}
if (line.Substring(0, 2) == "05")
{
counter++;
}
lines.add(line); //instead of writing, just adds the line to the temp list
if (sr.Peek() < 0)
{
sw.WriteLine(counter.ToString()); //writes everything left
foreach(var l in lines)
sw.WriteLine(l);
}
isFirstLine = false;
}
sr.Close();
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Exception finally block.");
}