c# - 用 '\r\n' 分割文本

标签 c# string split

我在关注这个 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/

相关文章:

c# - 为什么我不能使用扩展方法隐式转换委托(delegate)?

c# - MVC : Component gets rendered, 中的 Blazor 但 @onclick 不工作。连接问题

java - 来自属性文件 : Java 的字符串主机名

C++ string.compare()

c# - string.Split 忽略分隔符之间的空值

c# - 正则表达式在特定单词后立即查找单词

c# - Visual Studio 中有没有办法将文本转换为 C# 字符串文字?

php - 从php中的字符串中删除转义序列

java - 案例研究 : Is this an effective way to split a file?

Python - 正确提取拆分列表