How to convert a line with newline characters to it to separate lines?

How to convert a string from \r\nto strings?

For example, take this line:

string source = "hello \r\n this is a test \r\n tested";

and how can I convert it to:

string[] lines ;

//lines[0] = hello;
//lines[1] = this is a test;
//lines[2] = tested ;
+1
source share
5 answers

Use the String.Split Method (String [], StringSplitOptions) as follows:

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

This one will work whether the source is written using line line line \r\nor Unix \n.

As other answers you can use StringSplitOptions.RemoveEmptyEntriesinstead StringSplitOptions.None, which, as the name says, removes empty lines ( " "cannot be empty, only "").

+3
source

string.Split Regex.Split, .

var lines = Regex.Split( source, @"\r\n" );
+1

Try

string[] items = source.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
0
string text = "Hello \r\n this is a test \r\n tested";
string[] lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines) {
    System.Diagnostics.Debug.WriteLine(line);
}

System.String.Split , . StringSplitOptions , . ( , , , , )

0

.

:

ReadLines . ReadAllLines .

:

var lines = source.ReadAllLines();

File.ReadLines File.ReadAllLines, .Net framework.

StringReader.ReadLine, \r\n \n, Mac OS Os .. (shouldn ' t ).

public static class StringExtensions
{
    public static IEnumerable<string> ReadLines(this string data)
    {
        using (var sr = new StringReader(data))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
                yield return line;
        }
    }

    public static string[] ReadAllLines(this string data)
    {
        var res = new List<string>();

        using (var sr = new StringReader(data))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
                res.Add(line);
        }

        return res.ToArray();
    }
}

(ReadAllLines ReadLines.ToArray, , , IEnumerable, )

0

Source: https://habr.com/ru/post/1760727/


All Articles