读取流中的一行(对我来说,它实际上是COM端口上的流)时,返回的字符串不包含\ n或\ r字符(或\ r \ n组合)。为了记录目的,我想保留它们。目前,我的循环如下所示:
while (newPort.BytesToRead > 0)
{
received = ReadLine(newPort);
response.Add(received);
}
因此,基本上,我正在读取一个字符串,然后将其添加到名为
response
的字符串列表中。我想要的是返回的字符串received
包含原始流中的\ r或\ n或\ r \ n,以及终止一行文本。这很可能吗?甚至不平凡!
我猜这很难做到。我的意思是考虑一下,如果收到\ r,则必须获取下一个字符以查看它是否为\ n。如果没有下一个字符,我将超时并例外。如果存在下一个字符而不是\ n,则必须在下一次迭代中将其设置为当前字符,依此类推...!
最佳答案
这是问题帖子中OP的解决方案:
好吧,我对此很了解。我认为这是正确的...:
{
int s = 0, e = 0;
for (; e < line.Length; e++)
{
if (line[e] == '\n')
{
// \n always terminates a line.
lines.Add(line.Substring(s, (e - s) + 1));
s = e + 1;
}
if (line[e] == '\r' && (e < line.Length - 1))
{
// \r only terminates a line if it isn't followed by \n.
if (line[e + 1] != '\n')
{
lines.Add(line.Substring(s, (e - s) + 1));
s = e + 1;
}
}
}
// Check for trailing characters not terminated by anything.
if (s < e)
{
lines.Add(line.Substring(s, (e - s)));
}
}