Split Java String by New Line
To split a string in Java by new line, you can use the split
method of the String
class and pass it the regular expression "\n"
or "\r\n"
, depending on the platform you are running on.
Here's an example of how to split a string by new line using the split
method:
String input = "Hello\nWorld\n!";
String[] lines = input.split("\n");
for (String line : lines) {
System.out.println(line);
}
This will output the following:
Hello World !
The split
method returns an array of strings, with each element representing a line from the original string.
Note that the "\n"
regular expression will work on Unix-based systems, such as Linux and MacOS, where the new line character is represented by a single line feed character ('\n'
). On Windows, the new line character is represented by a combination of a carriage return ('\r'
) and a line feed ('\n'
), so you will need to use the regular expression "\r\n"
to split the string by new line on Windows.
You can also use the Scanner
class to split a string by new line. To do this, you can use the following code:
import java.util.Scanner;
String input = "Hello\nWorld\n!";
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
This will output the same result as the previous example.