EN
C# / .NET - split string by new line character
0 points
In this article, we would like to show how to split string by new line character in Java.
Quick solution:
xxxxxxxxxx
1
string originalString = "Some text";
2
3
// split string by new line - \n
4
String[] splittedString = originalString.Split("\n");
5
6
// split string by regex - \r?\n
7
// \r? - optional
8
// this regex will support most important platforms:
9
// - Windows - \r\n
10
// - UNIX / Linux / MacOS - \n
11
String[] splittedString = Regex.Split(originalString, "\r?\n");
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(string[] args)
6
{
7
string originalString =
8
"How\n" +
9
"to\n" +
10
"split\n" +
11
"\n" +
12
"\n" +
13
"string";
14
15
string[] splittedStrings = originalString.Split("\n");
16
Console.WriteLine("# Original string: ");
17
Console.WriteLine(originalString);
18
Console.WriteLine();
19
20
Console.WriteLine("# Split by new line character: ");
21
int counter = 1;
22
foreach (string stringElement in splittedStrings)
23
{
24
Console.WriteLine(counter + " - " + stringElement);
25
counter++;
26
}
27
}
28
}
Output:
xxxxxxxxxx
1
# Original string:
2
How
3
to
4
split
5
6
7
string
8
9
10
# Split by new line character:
11
1 - How
12
2 - to
13
3 - split
14
4 -
15
5 -
16
6 - string
3. C# split string by regex - \r?\n
- support for most important platforms Windows, Unix, Linux MacOS
Edit xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
string originalString =
9
"How\n" +
10
"to\r\n" +
11
"split\r\n" +
12
"\n" +
13
"\r\n" +
14
"string";
15
16
string[] splittedStrings = Regex.Split(originalString, "\r?\n");
17
Console.WriteLine("# Original string: ");
18
Console.WriteLine(originalString);
19
Console.WriteLine();
20
21
Console.WriteLine("# Split by new line character: ");
22
int counter = 1;
23
foreach (string stringElement in splittedStrings)
24
{
25
Console.WriteLine(counter + " - " + stringElement);
26
counter++;
27
}
28
}
29
}
Output:
xxxxxxxxxx
1
# Original string:
2
How
3
to
4
split
5
6
7
string
8
9
10
# Split by new line character:
11
1 - How
12
2 - to
13
3 - split
14
4 -
15
5 -
16
6 - string