我需要在. net中将字符串分割为换行符,我所知道的分割字符串的唯一方法是使用split方法。然而,这将不允许我(容易)在换行上分裂,那么最好的方法是什么?


当前回答

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

其他回答

要拆分一个字符串,你需要使用一个字符串数组的重载:

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

编辑: 如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将正确地拆分任意类型的换行,并保留文本中的空行和空格:

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

我只是想加上我的二进制,因为这个问题的其他解决方案不属于可重用代码分类,不方便。

下面的代码块扩展了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”作为分隔符参数。

评论:如果微软能实现这个重载就太好了。

尽量避免使用字符串。分割是一种通用的解决方案,因为在使用函数的任何地方都会使用更多的内存——原始字符串和分割副本,都在内存中。相信我,当你开始扩展时,这可能是一个非常严重的问题——运行一个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;
        }
    }
}

这将允许你在你的数据周围做一个更有效的内存循环;

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

当然,如果你想把它都放在内存中,你可以这样做;

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

你应该能够很容易地分割你的字符串,就像这样:

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

从。net 6开始,我们可以使用新的string . replacelineends()方法来规范化跨平台的行结束符,所以现在我发现这是最简单的方法:

var lines = input
  .ReplaceLineEndings()
  .Split(Environment.NewLine, StringSplitOptions.None);