Split a string on newlines in C#
To split a string on newlines in C#, we can use built in string methodSplit(param1, param2)
.Param1: we use
Environment.NewLine
to specify the new line delimiter.Param2: we use
StringSplitOptions.RemoveEmptyEntries
to remove empty entries which represents empty lines here.Example
using System;
public class Example
{
public static void Main()
{
string lines = @"Hello
Welcom
To
Mockstacks.com";
string[] strings = lines.Split(Environment.NewLine,StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(strings[0]);
Console.WriteLine(strings[1]);
Console.WriteLine(strings[2]);
Console.WriteLine(strings[3]);
}
}
Output
Hello
Welcom
To
Mockstacks.com
Welcom
To
Mockstacks.com