[英]C# Roll back Streamreader 1 character
對於 C# 項目,我正在使用流式閱讀器,我需要 go 后退 1 個字符(基本上就像撤消一樣),我需要它進行更改,因此當您獲得下一個字符時,它與您回滾時相同
例如
你好
我們的確是
H
乙
大號
大號
○
[空白]
噸
H
乙
R <-- 我們撤消 R
所以..
R <--撤銷
R
乙
這是一個粗略的想法
當您不知道是否需要該值時,請使用Peek()
而不是Read()
) - 然后您可以在不推進 stream 的情況下檢查該值。 另一種方法(我在我的一些代碼中使用)是將讀取器(或在我的情況下為Stream
)封裝在 class 中,該緩沖區具有內部緩沖區,可讓您將值推回。 始終首先使用緩沖區,從而可以輕松地將值(甚至:調整后的值)推回 stream 而無需倒回它(這不適用於許多流)。
一個干凈的解決方案是從 StreamReader 派生一個 class 並覆蓋 Read() function。
對於您的要求,一個簡單的private int lastChar
就足以實現 Pushback() 方法。 更通用的解決方案是使用Stack<char>
來允許無限制的推回。
//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;
}
}
position 減一:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.