【问题标题】:Split text with '\r\n'用 '\r\n' 分割文本
【发布时间】:2014-04-06 18:12:34
【问题描述】:

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

我想我应该得到这个结果,但不知何故我错过了一些东西......

【问题讨论】:

  • 为什么不使用File.ReadAllLinesFile.ReadLines
  • Console.WriteLine() 将在数组中的每个字符串之后自动添加换行符。您想在循环之前将这些行合并在一起,或者按照一个答案的建议,在 Split 文本之前替换 \n
  • 我想要以\r\n 而不是\n\r 结尾的行。
  • 问题不在于你最后有\r\n\n,而是你忘记了这些行实际上已经包含换行符。因此,即使您删除它们,文件中也只有三行。
  • 确定输出的第一行以\r\n结尾吗?添加这一行,看看是否是你所期望的:Console.WriteLine("lines.Length={0}", lines.Length);

标签: c# string split


【解决方案1】:

问题不在于拆分,而在于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
【解决方案2】:

这对我有用。

using System.IO;

//  

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

【讨论】:

    【解决方案3】:

    我认为问题出在您的文本文件中。它可能已经分成太多行,当您阅读它时,它会“添加”额外的\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);
    

    【讨论】:

    • 但是我为什么要加呢?
    【解决方案4】:

    我采用了一种更紧凑的方法将来自文本区域的输入拆分为字符串列表。如果适合您的目的,您可以使用它。

    问题是你不能用 \r\n 分割所以我事先删除了 \n 并且只用 \r 分割

    var serials = model.List.Replace("\n","").Split('\r').ToList<string>();
    

    我喜欢这种方法,因为您只需一行即可完成。

    【讨论】:

      【解决方案5】:

      这对我有用。

      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 文本。 (读取文件时\变成\\)。

      【讨论】:

        【解决方案6】:

        使用静态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]", " "));
        

        【讨论】:

          【解决方案7】:

          以下代码给出了预期的结果。

          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);
          

          【讨论】:

            【解决方案8】:

            在 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):
            微软无衬线
            9
            真的

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-10-20
              • 1970-01-01
              相关资源
              最近更新 更多