➤ Sum of digits in a String
➤ Count No of Vowels String
➤ String Pattern Programs in Java
➤ Take String Input In Java
➤ Take Multiple String Input in Java
➤ How To Reverse a String In Java
➤ Remove Special Characters
➤ String – Remove Character
➤ String Palindrome In Java
➤ Sort String In Java
➤ How to Compare Strings In Java
➤ Second Occurrence of Character
➤ Replace nth Occurrence String
➤ Last Occurrence of Character
➤ Uppercase & Lowercase
➤ Java Check If Char is Uppercase
➤ Check If String is Uppercase
➤ Swap Characters in String Java
➤ Java String indexOf() Method
➤ How to Replace Dot in Java?
➤ How to Find Length of String
➤ Substring Method In Java
➤ Split Method In Java
Split String By Line in Java | Sometimes string may contain multiple paragraphs separated by lines, and we need to split them based on the line. Here we will discuss how to split a string by a new line in Java.
To split strings in Java we can take the help of the split() method. The split() method given in the Java String class is used to divide the string into an array of strings based on some regular expression. To split a string based on the line we can use the ‘\n’ character which represents a line.
Program to Split String By Line in Java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String string = "Hi.\nHow are you?\nAre you eating?";
String[] lines = string.split("\n");
System.out.println(Arrays.toString(lines));
}
}
Output:-
[Hi., How are you?, Are you eating?]
We have taken a string that contains multiple lines and we want to split it based on the lines. For this, we have called the String class split() method by passing ‘\n’ as a regular expression. The resultant strings are stored in the array of strings.
To display an array of strings we have used the toString() method of the Java Arrays class. It converts an array to a string. But if we want to display elements separately then we can take the help of for or for-each loop.
public class Main {
public static void main(String[] args) {
String string = "Hi.\nHow are you?\nAre you eating?";
String[] lines = string.split("\n");
for (String line : lines) {
System.out.println(line);
}
}
}
Output:-
Hi.
How are you?
Are you eating?
Let us see another program to split string by new line in Java.
public class Main {
public static void main(String[] args) {
String string = "Hello\nWorld\nJava";
String[] lines = string.split("\n");
for (String line : lines) {
System.out.println(line);
}
}
}
Output:-
Hello
World
Java
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!