public class JavaStringSplitNewlineExample { public static void main(String[] args) { String nixSampleLine = "splitLine 1 \n splitLine 2 \n splitLine 3 \n splitLine 4"; String[] lines = nixSampleLine.split("\\r?\\n"); for (String line : lines) { System.out.println(line); } } }Observe the output of the code below:
splitLine 1 splitLine 2 splitLine 3 splitLine 4Though our strings were broken line by line, notice that they are untrimmed. Now let's try the same implementation in a different platform.
public class JavaStringSplitNewlineExample { public static void main(String[] args) { String winSampleLine = "splitLine 1 \r\n splitLine 2 \r\n splitLine 3 \r\n splitLine 4"; String[] lines = winSampleLine.split("\\r?\\n"); for (String line : lines) { System.out.println(line); } } }Observe the output of the code below:
splitLine 1 splitLine 2 splitLine 3 splitLine 4Once again, just like the result from the *Nix Environment, the lines are not trimmed.
public class JavaStringSplitNewlineExample { public static void main(String[] args) { String winSampleLine = "splitLine 1 \r\n splitLine 2 \r\n splitLine 3 \r\n splitLine 4"; String[] lines = winSampleLine.split("\\s*\\r?\\n\\s*"); for (String line : lines) { System.out.println(line); } } }Understand that the appended sequence of zero or more white space on both sides of ( \r?\n) is what the expression (\s*) is used for. We altered the version of the regular expression ( \r?\n), thereby making the String split and trimmed.
Check out the result below:
splitLine 1 splitLine 2 splitLine 3 splitLine 4