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


当前回答

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

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

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

其他回答

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

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

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

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

我的尝试是:

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

编辑:

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

愚蠢的回答:写到一个临时文件,这样你就可以使用可敬的 文件。readline

var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
    writer.Write(s);
}
var lines = File.ReadLines(path);
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);
        }
    }
}

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

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