Grails Cookbook - A collection of tutorials and examples

Java String Split Newline

There are cases in which new line is used as a delimiter to split a java string. An example would be, when it is used to load the contents of a text document to a String if you want to break it line by line.

Split New Line

Note that lines are separated by the character "\n" in *Nix environment. This is not the case in Windows, for this type of platform, the separator is "\r\n". Now when you get the idea of merging the logic of the two platforms, you should know the correct regular expression in denoting line feeds is "\r?\n", thereby making "\n" a requirement, rather than "\r" which is optional.

Example of *Nix Line Feed

Check out below the written example for *Nix Environment:
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 4
Though our strings were broken line by line, notice that they are untrimmed. Now let's try the same implementation in a different platform.

Example of Windows Line Feed

Check out below the written example for Windows Environment:
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 4
Once again, just like the result from the *Nix Environment, the lines are not trimmed.

Split New Line with Trim()

Study and observe the program below, this is an example wherein not only each element will be trimmed, but also a modified version will be included as well.
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