Easiest way to split a string on newlines in .NET?

2018-12-31 15:27发布

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?

15条回答
妖精总统
2楼-- · 2018-12-31 15:46

Well, actually split should do:

//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]);
}
查看更多
步步皆殇っ
3楼-- · 2018-12-31 15:47

I did not know about Environment.Newline, but I guess this is a very good solution.

My try would have been:

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

The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.

EDIT:

As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.

查看更多
孤独总比滥情好
4楼-- · 2018-12-31 15:49

To split on a string you need to use the overload that takes an array of strings:

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

Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

string[] lines = theText.Split(
    new[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);
查看更多
看淡一切
5楼-- · 2018-12-31 15:53

What about using a StringReader?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
    string line = reader.ReadLine();
}
查看更多
唯独是你
6楼-- · 2018-12-31 15:53

Just thought I would add my two-bits because the other solutions on this question do not fall into the reusable code classification and are not convenient. The following block of code extends the string object so that it is available as a natural method when working with strings.

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

You can now use the .Split() function from any string as follows :

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

To split on a newline char, simply pass "\n" or "\r\n" as the delimiter parameter.

Comment : It would be nice if Microsoft implemented this overload.

查看更多
查无此人
7楼-- · 2018-12-31 15:56
string[] lines = text.Split(
  Environment.NewLine.ToCharArray(), 
  StringSplitOptions.RemoveEmptyStrings);

The RemoveEmptyStrings option will make sure you don't have empty entries due to \n following a \r

(Edit to reflect comments:) Note that it will also discard genuine empty lines in the text. This is usually what I want but it might not be your requirement.

查看更多
登录 后发表回答