[英]Writing to temp array from text file
我之前问过这个,但大多数人都不理解我的问题。
我有两个文本文件。 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
显然我应该首先将行写入临时字符串数组,计数然后写入计数,然后写入临时数组中的行。
我是新手,所以我一直想弄清楚我是如何实现这一目标的。
任何帮助将非常感谢。
尝试这个
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.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.