C# 在.NET的换行符上拆分字符串的最简单方法?

C# 在.NET的换行符上拆分字符串的最简单方法?,c#,.net,string,split,C#,.net,String,Split,我需要在.NET中将字符串拆分为换行符,我所知道的唯一拆分字符串的方法是使用该方法。但是,这不允许我(轻松地)在换行符上拆分,那么最好的方法是什么呢?要在字符串上拆分,需要使用接受字符串数组的重载: string[] lines = theText.Split( new[] { Environment.NewLine }, StringSplitOptions.None ); 编辑: 如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将在任何类型的换行符上正确拆

我需要在.NET中将字符串拆分为换行符,我所知道的唯一拆分字符串的方法是使用该方法。但是,这不允许我(轻松地)在换行符上拆分,那么最好的方法是什么呢?

要在字符串上拆分,需要使用接受字符串数组的重载:

string[] lines = theText.Split(
    new[] { Environment.NewLine },
    StringSplitOptions.None
);
编辑:
如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将在任何类型的换行符上正确拆分,并在文本中保留空行和间距:

string[] lines = theText.Split(
    new[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);

您应该能够非常轻松地拆分字符串,如下所示:

aString.Split(Environment.NewLine.ToCharArray());

我不知道环境。新线,但我想这是一个很好的解决方案

我的尝试是:

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

附加的.Trim将删除可能仍然存在的任何\r或\n(例如,在windows上使用os x换行符拆分字符串时)。也许不是最快的方法

编辑:


正如注释正确指出的那样,这也会删除行首或新行提要之前的任何空白。如果需要保留空白,请使用其他选项之一

实际上,拆分应该:

//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);

//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
    Console.WriteLine("{0}: {1}", i, splitted[i]);
}
//正在构造字符串。。。
StringBuilder sb=新的StringBuilder();
给某人加上一行(“第一行”);
某人的第二行(“第二行”);
某人的第三行(“第三行”);
字符串s=sb.ToString();
控制台。写入线(s);
//将多行字符串拆分为单独的行
string[]splitted=s.Split(新字符串[]{System.Environment.NewLine},StringSplitOptions.RemoveEmptyEntries);
//输出(单独的行)
对于(int i=0;i
RemoveEmptyStrings选项将确保您没有由于以下原因而产生的\n空项\r\n


(编辑以反映注释:)请注意,它还将丢弃文本中真正的空行。这通常是我想要的,但可能不是您的要求。

根据Guffa的回答,在扩展类中,使用:

public static string[] Lines(this string source) {
    return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}

对于字符串变量
s

s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
这将使用环境中的线端点定义。在Windows上,行尾是CR-LF(回车、换行)或C#的转义字符
\r\n

这是一个可靠的解决方案,因为如果将行与重新组合,则等于原始字符串:

var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);

不要做什么:

  • 使用,因为这将破坏标记,例如空行具有语法用途的标记
  • 在分隔符
    newchar[]{Environment.NewLine}
    上拆分,因为在Windows上,这将为每一新行创建一个空字符串元素

    • 愚蠢的回答:写一个临时文件,这样你就可以使用尊者

      使用一个新的工具怎么样


      Regex也是一个选项:

          private string[] SplitStringByLineFeed(string inpString)
          {
              string[] locResult = Regex.Split(inpString, "[\r\n]+");
              return locResult;
          }
      

      我目前正在VB.NET中使用此函数(基于其他答案):

      私有共享函数将行(文本作为字符串)拆分为字符串()
      返回text.Split({Environment.NewLine,vbCrLf,vbLf},StringSplitOptions.None)
      端函数
      
      它首先尝试在平台本地换行符上拆分,然后返回到每个可能的换行符

      到目前为止,我只在一个班里需要这个。如果这种情况发生变化,我可能会将此
      公开
      ,并将其移动到实用程序类,甚至可能将其作为扩展方法

      以下是如何将线路连接起来,以便更好地测量:

      私有共享函数JoinLines(作为IEnumerable的行(字符串))作为字符串
      返回String.Join(Environment.NewLine,line)
      端函数
      
      使用System.IO;
      字符串textToSplit;
      if(textToSplit!=null)
      {
      列表行=新列表();
      使用(StringReader=新StringReader(textToSplit))
      {
      for(string line=reader.ReadLine();line!=null;line=reader.ReadLine())
      {
      行。添加(行);
      }
      }
      }
      
      尽量避免使用string.Split作为一般解决方案,因为在使用函数的任何地方都会使用更多的内存--原始字符串和拆分副本,两者都在内存中。相信我,当您开始扩展时,这可能是一个非常严重的问题--运行一个32位批处理应用程序处理100MB文档,您将浪费8个并发线程。并不是说我以前去过那里

      相反,使用这样的迭代器

          public static IEnumerable<string> SplitToLines(this string input)
          {
              if (input == null)
              {
                  yield break;
              }
      
              using (System.IO.StringReader reader = new System.IO.StringReader(input))
              {
                  string line;
                  while( (line = reader.ReadLine()) != null)
                  {
                      yield return line;
                  }
              }
          }
      
      当然,如果你想把它全部记在内存中,你可以这样做

      var allTheLines = document.SplitToLines.ToArray();
      

      我只是想添加我的两位,因为这个问题的其他解决方案不属于可重用代码分类,也不方便

      下面的代码块扩展了
      string
      对象,使其在处理字符串时可以作为自然方法使用

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Collections;
      using System.Collections.ObjectModel;
      
      namespace System
      {
          public static class StringExtensions
          {
              public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
              {
                  return s.Split(new string[] { delimiter }, options);
              }
          }
      }
      
      您现在可以从任何字符串使用
      .Split()
      函数,如下所示:

      string[] result;
      
      // Pass a string, and the delimiter
      result = string.Split("My simple string", " ");
      
      // Split an existing string by delimiter only
      string foo = "my - string - i - want - split";
      result = foo.Split("-");
      
      // You can even pass the split options parameter. When omitted it is
      // set to StringSplitOptions.None
      result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
      
      要在换行符上拆分,只需传递
      “\n”
      “\r\n”
      作为分隔符参数

      评论:如果微软能实现这种超负荷,那就太好了。

      实际上非常简单

      VB.NET:

      Private Function SplitOnNewLine(input as String) As String
          Return input.Split(Environment.NewLine)
      End Function
      
      C#:


      这里的例子非常好,帮助我解决了当前的一个“难题”,即拆分RSA密钥,以更具可读性的方式呈现。基于解决方案:

          string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
          {
              //Spit each string into a n-line length list of strings
              var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
              
              //Check if there are any characters left after split, if so add the rest
              if(txt.Length > ((txt.Length / n)*n) )
                  Lines.Add(txt.Substring((txt.Length/n)*n));
      
              //Create return text, with extras
              string txtReturn = "";
              foreach (string Line in Lines)
                  txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
              return txtReturn;
          }
      
      提供一个具有33个字符宽度和引号的RSA密钥非常简单

      Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));
      
      输出:


      希望有人觉得它有用…

      为什么不呢?只需在System.Environment.NewLine上拆分,但您必须将其包装在字符串[]中,并添加一个额外的参数,然后。。。在一个非*nix系统上,它会在换行符字符串中的单独字符(即CR和LF字符)上拆分。这将导致每行之间出现一个额外的空字符串。@RCIX:No,代码\r和\n表示单个字符。字符串“\r\n”是两个字符,而不是四个字符。如果添加参数StringSplitOptions.RemoveEmptyEntries,则这将非常有效。@Ruben:不,不会。Serge在他的回答中已经提出了这一点,我有一个建议
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Collections;
      using System.Collections.ObjectModel;
      
      namespace System
      {
          public static class StringExtensions
          {
              public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
              {
                  return s.Split(new string[] { delimiter }, options);
              }
          }
      }
      
      string[] result;
      
      // Pass a string, and the delimiter
      result = string.Split("My simple string", " ");
      
      // Split an existing string by delimiter only
      string foo = "my - string - i - want - split";
      result = foo.Split("-");
      
      // You can even pass the split options parameter. When omitted it is
      // set to StringSplitOptions.None
      result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
      
      Private Function SplitOnNewLine(input as String) As String
          Return input.Split(Environment.NewLine)
      End Function
      
      string splitOnNewLine(string input)
      {
          return input.split(environment.newline);
      }
      
          string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
          {
              //Spit each string into a n-line length list of strings
              var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
              
              //Check if there are any characters left after split, if so add the rest
              if(txt.Length > ((txt.Length / n)*n) )
                  Lines.Add(txt.Substring((txt.Length/n)*n));
      
              //Create return text, with extras
              string txtReturn = "";
              foreach (string Line in Lines)
                  txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
              return txtReturn;
          }
      
      Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));