我在关注这个 article
我想出了这段代码:
string FileName = "C:\\test.txt";
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string[] stringSeparators = new string[] { "\r\n" };
string text = sr.ReadToEnd();
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in lines)
{
Console.WriteLine(s);
}
}
这是示例文本:
somet interesting text\n
some text that should be in the same line\r\n
some text should be in another line
这是输出:
somet interesting text\r\n
some text that should be in the same line\r\n
some text should be in another line\r\n
但我想要的是:
somet interesting textsome text that should be in the same line\r\n
some text should be in another line\r\n
我想我应该得到这个结果,但不知何故我遗漏了一些东西......
最佳答案
问题不在于拆分,而在于 WriteLine
。使用 WriteLine
打印的字符串中的 \n
将产生“额外”行。
例子
var text =
"somet interesting text\n" +
"some text that should be in the same line\r\n" +
"some text should be in another line";
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
Console.WriteLine(s); //But will print 3 lines in total.
}
要解决此问题,请在打印字符串之前删除 \n
。
Console.WriteLine(s.Replace("\n", ""));
关于c# - 用 '\r\n' 分割文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185009/