C# 在StreamReader中读取下一个字符
如何使用streamreader读取下一个字符并继续索引? 例如,如果文件有“Hello”,我希望在第一次迭代中得到H,并且能够在不破坏循环的情况下得到E。 如果我读()的话,我会丢失当前的索引,希望我能告诉你们C# 在StreamReader中读取下一个字符,c#,C#,如何使用streamreader读取下一个字符并继续索引? 例如,如果文件有“Hello”,我希望在第一次迭代中得到H,并且能够在不破坏循环的情况下得到E。 如果我读()的话,我会丢失当前的索引,希望我能告诉你们 using (StreamReader sr = new StreamReader(inpFil.Pth)) { while (sr.Peek() >= 0 ) { char c = (char)sr.Read(); char r
using (StreamReader sr = new StreamReader(inpFil.Pth))
{
while (sr.Peek() >= 0 )
{
char c = (char)sr.Read();
char r = (char)sr.Read();
}
}
我想你在追求这样的东西:
using (StreamReader sr = new StreamReader("inpFil.Pth"))
{
if (sr.Peek() < 0)
return; // No data.
char current = (char)sr.Read(); // Can't be -1 due to Peek() test above.
while (sr.Peek() >= 0)
{
char next = (char)sr.Read(); // Can't be -1 due to Peek() test above.
// Add code here to do something with current and next.
current = next;
}
// Add code here to handle the special case of the last char in
// the file, where you have 'current' but no 'next'.
}
你的意思是你想在循环中使用“当前”和“下一个”字符吗?
Peek
-就像你已经在使用…@MatthewWatson是的,我不想失去电流one@mjwills,但到,我需要使用read()来读取它,我将丢失当前的,对于下一个循环,我将得到i+2,我认为需求是一个保持(当前,下一个)值的循环,这样对于循环的任何迭代,下一个迭代将current
设置为该迭代的next
,并且next
将设置为以下字符。如果在循环中有两次读取,则无法实现该功能。您必须只有一次读取,并操作当前
和下一个
变量,以保持从一次迭代到下一次迭代的状态。
using (StreamReader sr = new StreamReader("inpFil.Pth"))
{
while (sr.Peek() >= 0)
{
char current = (char)sr.Read();
if (sr.Peek() < 0) // No next?
{
// Add code here to handle 'current' for special "last char" case.
break;
}
char next = (char)sr.Peek();
// Add code here to do something with current and next.
}
}