首页 文章

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

提问于
浏览
665

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

15 回答

  • 41

    嗯,实际上拆分应该做:

    //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]);
    }
    
  • 1

    傻回答:写一个临时文件,这样就可以使用古老的File.ReadLines

    var s = "Hello\r\nWorld";
    var path = Path.GetTempFileName();
    using (var writer = new StreamWriter(path))
    {
        writer.Write(s);
    }
    var lines = File.ReadLines(path);
    
  • 0

    怎么样使用StringReader

    using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
        string line = reader.ReadLine();
    }
    
  • -1

    我不知道Environment.Newline,但我想这是一个非常好的解决方案 .

    我的尝试本来是:

    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换行符分割字符串时) . 可能不是最快的方法 .

    编辑:

    正如评论正确指出的那样,这也会删除行开头或新换行符之前的任何空格 . 如果需要保留该空格,请使用其他选项之一 .

  • -1
    string[] lines = text.Split(
      Environment.NewLine.ToCharArray(), 
      StringSplitOptions.RemoveEmptyStrings);
    

    RemoveEmptyStrings选项将确保由于\ n后面的\ n而没有空条目

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

  • 6

    实际上非常简单 .

    VB.NET:

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

    C#:

    string splitOnNewLine(string input)
    {
        return input.split(environment.newline);
    }
    
  • 1184

    要拆分字符串,您需要使用带有字符串数组的重载:

    string[] lines = theText.Split(
        new[] { Environment.NewLine },
        StringSplitOptions.None
    );
    

    编辑:
    如果要在文本中处理不同类型的换行符,可以使用匹配多个字符串的功能 . 这将正确分割任何类型的换行符,并保留文本中的空行和间距:

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

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

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

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

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

    对于字符串变量 s

    s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
    

    这将使用您的环境's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#' s转义字符 \r\n .

    这是一个可靠的解决方案,因为如果您使用String.Join重新组合这些行,则这等于您的原始字符串:

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

    什么不该做:

    • 使用StringSplitOptions.RemoveEmptyEntries,因为这会破坏标记,例如Markdown,其中空行具有语法用途 .

    • 拆分分隔符 new char[]{Environment.NewLine} ,因为在Windows上,这将为每个新行创建一个空字符串元素 .

  • 4

    正则表达式也是一个选项:

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

    尽量避免使用string.Split作为一般解决方案,因为在使用该函数的任何地方都会使用更多内存 - 原始字符串和拆分副本都在内存中 . 请相信我,当你开始扩展时,这可能是一个问题 - 运行一个处理100MB文档的32位批处理应用程序,你将在八个并发线程中废弃 . 不是说我以前去过那里......

    相反,使用这样的迭代器;

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

    这将允许您围绕数据执行更高效的内存循环;

    foreach(var line in document.SplitToLines()) 
    {
        // one line at a time...
    }
    

    当然,如果你想要所有内存,你可以做到这一点;

    var allTheLines = document.SplitToLines.ToArray();
    
  • 24

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

    Private Shared Function SplitLines(text As String) As String()
        Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
    End Function
    

    它首先尝试拆分平台本地换行符,然后回退到每个可能的换行符 .

    到目前为止,我只在一个 class 里面需要这个 . 如果这改变了,我可能会把它变成 Public 并将其移动到实用程序类,甚至可能使它成为扩展方法 .

    以下是如何将备份线连接起来,以获得良好的衡量标准:

    Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
        Return String.Join(Environment.NewLine, lines)
    End Function
    
  • 90

    只是想我会添加我的两位,因为这个问题上的其他解决方案不属于可重用的代码分类并且不方便 . 下面的代码块扩展了 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 param. when omitted it is
    // set to StringSplitOptions.None
    result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
    

    要拆分换行符,只需将 "\n""\r\n" 作为分隔符参数传递 .

    Comment : 如果Microsoft实现了这个重载会很好 .

  • -3
    // using System.IO;
    
    string textToSplit;
    
      if(textToSplit!=null)
       {
        List<string> lines = new List<string>();
        using (StringReader reader = new StringReader(textToSplit))
        {
            for (string line = reader.ReadLine(); line != null;line = reader.ReadLine())
            {
                lines.Add(line);
            }
        }
       }
    

相关问题