使用'\r\n'分割文本

51

我遵循了这篇文章

然后我写出了这段代码:

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

我认为我应该得到这个结果,但不知道为什么有些东西缺失了...


4
为什么不使用 File.ReadAllLinesFile.ReadLines - Tim Schmelter
Console.WriteLine() 会在你的数组中每个字符串后自动添加换行符。你需要在循环之前将这些行合并,或者像一个答案建议的那样,在 Split 文本之前替换掉 \n - dub stylee
我想要一行代码,它特别以\r\n结尾,而不是\n\r - skmasq
2
问题不在于你的文件末尾有\r\n\n,而是你忘记了这些行已经包含了换行符。因此,即使你将它们删除,文件中仍然有三行。 - Tim Schmelter
你确定输出的第一行是否以“\r\n”结尾?添加以下代码并查看结果是否符合预期:Console.WriteLine("lines.Length={0}", lines.Length); - Austin Salonen
9个回答

71
问题不在于分割,而在于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", ""));

是的,Console.WriteLine()\n 转换为 \r\n - skmasq

13

这对我起作用了。

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);

6

我认为问题在您的文本文件中。它可能已经分成太多行,当您读取时,会“添加”额外的\r和/或\n字符(因为它们存在于文件中)。检查一下text变量读取到了什么。

以下代码(在本地变量与您的文本)可以正常工作并分为2行:

string[] stringSeparators = new string[] { "\r\n" };
string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line";
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

但是我为什么要添加它呢? - Szymon

6
我采用更紧凑的方法将文本区域输入分割成字符串列表。如果适用于您的目的,您可以使用此方法。
问题在于您无法按\r\n拆分,因此我事先删除了\n并仅按\r拆分。
var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

我喜欢这种方法,因为你只需要一行代码就可以完成。

3

使用静态File类更易读取文件:

// First read all the text into a single string.
string text = File.ReadAllText(FileName);

// Then split the lines at "\r\n".   
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

// Finally replace lonely '\r' and '\n' by  whitespaces in each line.
foreach (string s in lines) {
    Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
}

注意:文本中可能包含垂直制表符\v,这些是Microsoft Word用作手动换行符。
为了捕获任何可能的换行符,可以使用正则表达式进行替换。
Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));

1
这对我起作用了。
string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

第一个替换将文本文件的新行中的\r\n替换掉,第二个替换将实际的\r\n文本替换为读取文件时转换为\\r\\n的文本。(当文件被读取时,\变成了\\)。

1
在Winform应用程序(C#)中:
static string strFilesLoc = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"..\..\")) + "Resources\\";
    public static string[] GetFontFamily()
            {
                var result = File.ReadAllText(strFilesLoc + "FontFamily.txt").Trim();
                string[] items = result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                return items;
            }

在文本文件中(FontFamily.txt):
Microsoft Sans Serif
9
true


0

Split 只能使用单个字符,并且需要像 '|' 或 '\n' 这样的单引号,但 \r\n 是一个字符串,因此不能与 Split 一起使用。请改用正则表达式。

string[] lines=Regex.Split(str, "\r\n");

不要忘记使用 using System.Text.RegularExpressions;

0

以下代码可以得到预期的结果。

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接