gpt4 book ai didi

c# - StringReader 省略尾随换行符

转载 作者:行者123 更新时间:2023-11-30 14:58:17 33 4
gpt4 key购买 nike

我注意到在 StreamReaderStringReader 上使用 ReadLine() 时,如果文件或字符串以换行符结尾,该字符序列完全丢失。考虑以下示例:

static void Main(string[] args)
{
string data = "First Line\r\nSecond Line\r\n\r\n\r\n";
List<string> lineData = new List<string>();
string[] splitData = data.Split(
new string[] { "\r\n" },
StringSplitOptions.None);

using (StringReader sr = new StringReader(data))
{
string line;
while ((line = sr.ReadLine()) != null)
lineData.Add(line);
}

Console.WriteLine("Raw Line Count: " + splitData.Length);
Console.WriteLine("StringReader Line Count: " + lineData.Count);
Console.WriteLine("Split Data: ");
foreach (string s in splitData)
Console.WriteLine(string.IsNullOrEmpty(s) ? "[blank line]" : s);
Console.WriteLine("StringReader Data: ");
foreach (string s in lineData)
Console.WriteLine(string.IsNullOrEmpty(s) ? "[blank line]" : s);
Console.ReadKey();
}

输出是这样的:

Raw Line Count: 5
StringReader Line Count: 4
Split Data:
First Line
Second Line
[blank line]
[blank line]
[blank line]
StringReader Data:
First Line
Second Line
[blank line]
[blank line]

为什么 StringReader/StreamReader 会这样?我可以想到几种解决方法,但由于读者的行为出乎意料,因此不得不重新编写我的代码似乎很愚蠢。某些 .NET 库中是否有某些设置会影响流处理最终换行符的方式?

编辑

这是另一个示例:比较运行示例时的结果,首先与 "First Line\r\nSecond Line" 比较,然后与 "First Line\r\nSecond Line\r\n “。结果完全相同(就示例的 StringReader 部分而言)。为什么 StringReader 在第二个示例中返回 null 而不是空字符串?我知道从 ReadLine() 返回的字符串不包含换行符,但为什么最后一行会被解释为 null 而不是 ""?

最佳答案

这是预期的行为并记录在案。来自 - http://msdn.microsoft.com/en-us/library/system.io.stringreader.readline.aspx .

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed. The returned value is null if the end of the string has been reached.

意味着最后返回的值是空的,它会省略最后一个换行符。如果需要在读取数据中显示,可以通过uisng Environment.NewLine重新申请。

关于c# - StringReader 省略尾随换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365404/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com