EN
Java - split string by new line character
6 points
xxxxxxxxxx
1
String example = "...";
2
3
// split string by new line - \n
4
String[] split1 = example.split("\n");
5
6
// split string by regex - \\r?\\n
7
// \\r? - this is optional
8
// so this regex will support most important platforms:
9
// - Windows - \r\n
10
// - UNIX / Linux / MacOS - \n
11
String[] split2 = example.split("\\r?\\n");
Code example:
xxxxxxxxxx
1
public class JavaSplitStringByNewLineExample1 {
2
3
public static void main(String[] args) {
4
5
String example =
6
"How\n" +
7
"to\n" +
8
"split\n" +
9
"\n" +
10
"\n" +
11
"string\n";
12
13
String[] split = example.split("\n");
14
System.out.println("# Original string: ");
15
System.out.println(example);
16
System.out.println();
17
18
System.out.println("# Split by new line character: ");
19
int cnt = 1;
20
for (String str : split) {
21
System.out.println(cnt + " - " + str);
22
cnt++;
23
}
24
}
25
}
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. Java split string by regex - \\r?\\n - support for most important platforms Windows, Unix, Linux MacOS
EditCode example with explanation in comment:
xxxxxxxxxx
1
public class JavaSplitStringByNewLineExample2 {
2
3
public static void main(String[] args) {
4
5
String example =
6
"How\n" +
7
"to\r\n" +
8
"split\r\n" +
9
"\n" +
10
"\r\n" +
11
"string\n";
12
13
// \\r?\\n
14
// \\r? - this is optional
15
// so this regex will support:
16
// - Windows - \r\n
17
// - UNIX / Linux / MacOS - \n
18
String[] split = example.split("\\r?\\n");
19
System.out.println("# Original string: ");
20
System.out.println(example);
21
System.out.println();
22
23
System.out.println("# Split by new line character: ");
24
int cnt = 1;
25
for (String str : split) {
26
System.out.println(cnt + " - " + str);
27
cnt++;
28
}
29
}
30
}
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