Languages
[Edit]
EN

C# / .NET - split string by new line character

0 points
Created by:
Pearl-Hurley
559

In this article, we would like to show how to split string by new line character in Java.

Quick solution:

string originalString = "Some text";

// split string by new line - \n
String[] splittedString = originalString.Split("\n");

// split string by regex - \r?\n
// \r? - optional
// this regex will support most important platforms:
// - Windows - \r\n
// - UNIX / Linux / MacOS - \n
String[] splittedString = Regex.Split(originalString, "\r?\n");

1. C# split string by new line - \n

using System;

public class Program
{
    public static void Main(string[] args)
    {
        string originalString =
                "How\n" +
                "to\n" +
                "split\n" +
                "\n" +
                "\n" +
                "string";

        string[] splittedStrings = originalString.Split("\n");
        Console.WriteLine("# Original string: ");
        Console.WriteLine(originalString);
        Console.WriteLine();

        Console.WriteLine("# Split by new line character: ");
        int counter = 1;
        foreach (string stringElement in splittedStrings)
        {
            Console.WriteLine(counter + " - " + stringElement);
            counter++;
        }
    }
}

Output:

# Original string:
How
to
split


string


# Split by new line character:
1 - How
2 - to
3 - split
4 -
5 -
6 - string

3. C# split string by regex - \r?\n - support for most important platforms Windows, Unix, Linux MacOS

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main(string[] args)
    {
        string originalString =
                        "How\n" +
                        "to\r\n" +
                        "split\r\n" +
                        "\n" +
                        "\r\n" +
                        "string";

        string[] splittedStrings = Regex.Split(originalString, "\r?\n");
        Console.WriteLine("# Original string: ");
        Console.WriteLine(originalString);
        Console.WriteLine();

        Console.WriteLine("# Split by new line character: ");
        int counter = 1;
        foreach (string stringElement in splittedStrings)
        {
            Console.WriteLine(counter + " - " + stringElement);
            counter++;
        }
    }
}

Output:

# Original string:
How
to
split


string


# Split by new line character:
1 - How
2 - to
3 - split
4 -
5 -
6 - string

Alternative titles

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - split string by new line character

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join