我有一个包含块(标题和正文)的文件。我需要分开块。标题是“he=”,正文可以是任何东西,例如“巨石很重”。所以一个典型的文件可能看起来像
he=晴天he=巨石很重he=大家好
我正在使用 StreamReader 的 Read 方法逐字符读取。
在程序中,我使用 if 语句检查 he 和 = 以确定它的标题。但是考虑一下沉重这个词。我需要一种将文件指针移回 h 的方法,因为它不是标题。
有没有办法可以在 StreamReader 中移动文件指针?上面的标题正文示例只是一个用于解释的玩具示例。
我有一个包含块(标题和正文)的文件。我需要分开块。标题是“he=”,正文可以是任何东西,例如“巨石很重”。所以一个典型的文件可能看起来像
he=晴天he=巨石很重he=大家好
我正在使用 StreamReader 的 Read 方法逐字符读取。
在程序中,我使用 if 语句检查 he 和 = 以确定它的标题。但是考虑一下沉重这个词。我需要一种将文件指针移回 h 的方法,因为它不是标题。
有没有办法可以在 StreamReader 中移动文件指针?上面的标题正文示例只是一个用于解释的玩具示例。
由于 StreamReader 仅向前,因此您无法向后退。然而,一切都没有丢失。一种常见的策略是使用缓冲区变量并检查它。这是一些粗略的代码:
var buffer = new StringBuilder();
while(streamReader.Peek() >= 0)
{
//Add latest character to buffer
buffer.append(streamReader.Read());
//Check the three rightmost characters in the buffer for the occurance of he=
if(buffer.Length >= 3 && buffer.ToString().Substr(buffer.Length-3, 3) == "he=")
{
//We have found new header. Now we trim the header from the rest of the buffer to get the body
var newBody = buffer.ToString().Substr(0,buffer.Length-3);
//I'm assuming you'll be adding the body somewhere
bodies.Add(newBody);
//Now we clear the buffer
buffer.Clear();
}
}
//What's left in the buffer is also a body
bodies.Add(buffer.ToString());