对于一个C#项目,我正在使用StreamReader,需要回退1个字符(基本上像撤销),并且需要更改,以便在获取下一个字符时,它与回滚时相同。例如:Hello There我们这样做H E L L O [空格] T H E R <-- 我们撤销了R,所以...R <-- 撤销了R R E 那是一个大致的想法。
Peek()
而非Read()
,这样你就可以在不推进流的情况下检查值。另一种方法(我在我的一些代码中使用)是将读取器(或在我的情况下,一个Stream
)封装在一个类中,该类具有内部缓冲区,可以让您推回值。缓冲区始终首先使用,因此很容易将值(甚至是调整后的值)推回流中,而无需倒回它(对于许多流来说这是不起作用的)。private int lastChar
就足以实现Pushback()方法。更一般的解决方案将使用Stack<char>
来允许无限的pushbacks。//untested, incomplete
class MyReader : StreamReader
{
public MyReader(Stream strm)
: base(strm)
{
}
private int lastChar = -1;
public override int Read()
{
int ch;
if (lastChar >= 0)
{
ch = lastChar;
lastChar = -1;
}
else
{
ch = base.Read(); // could be -1
}
return ch;
}
public void PushBack(char ch) // char, don't allow Pushback(-1)
{
if (lastChar >= 0)
throw new InvalidOperation("PushBack of more than 1 char");
lastChar = ch;
}
}
将位置减一:
var bytes = Encoding.ASCII.GetBytes("String");
Stream stream = new MemoryStream(bytes);
Console.WriteLine((char)stream.ReadByte()); //S
Console.WriteLine((char)stream.ReadByte()); //t
stream.Position -= 1;
Console.WriteLine((char)stream.ReadByte()); //t
Console.WriteLine((char)stream.ReadByte()); //r
Console.WriteLine((char)stream.ReadByte()); //i
Console.WriteLine((char)stream.ReadByte()); //n
Console.WriteLine((char)stream.ReadByte()); //g
StreamReader
,c: 不是所有的流都可寻址。 - Marc Gravell