How to Split a String on newlines in C#?

Ever wanted to split an input string in to new lines in .NET (c#) that has a new line character? Below is a sample code snippet that demonstrates how to do it.

How to Split a String on newlines in C#?

using System;

using System.Collections.Generic;

using System.Data;

using System.DirectoryServices.AccountManagement;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Sockets;

namespace AbundantCode

{

internal class Program

{

// How to Split a String on newlines in C# ?

private static void Main(string[] args)

{

string input = "ABundantcode.com \n is a \n Programming website";

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

foreach(var item in AllInputs)

Console.WriteLine(item);

Console.ReadKey();

}

}

}
How to Split a String on newlines in C#?
Tags :

2 Comments

  • You can do in this way also….

    string test = “One\nTwo\r\nThree\nFour\n”;
    string[] result = test.Split(new string[] { “\n”, “\r\n” }, StringSplitOptions.RemoveEmptyEntries);

    zene

  • Separates strings. Often strings have delimiter characters in their data. Delimiters include “\r\n” newline sequences and the comma and tab characters. Split handles splitting upon string and character delimiters.

    ASP.Net C# Split string function provides the functionality to split the string into a string array by specifying its delimiters. C# split string function splits the string into array collection according to the number of separators passed to the split function. ASP.Net C# split string function removes the delimiters from the string and stores each part separated at consecutive indexes of array object. In ASP.Net 2.0 C# split string function has 6 overloads as follows.
    for full implementation refer here: http://www.mindstick.com/Articles/996c0a4b-f9c0-4381-85a0-41da6d0c7f63/String%20Split%20in%20C

Leave Your Comment