How to split a java text block by lines?

336 views Asked by At

Let's say we have the following java text block :

         String textblock = """
                 A : 111
                 B : 111
                 C : 1111
                 """;

I would like to split it by lines to get the following result :

         String [] splitedTextBlock = splitTextBlockSomeHow(textblock); 
         // expected result : {"A : 111", "B : 222", "C : 333"}
2

There are 2 answers

2
Yaroslavm On BEST ANSWER
public static String[] splitTextBlock(String textblock) {
   return textblock.trim().split(System.lineSeparator());
}

...

String textblock = """
        A : 111
        B : 111
        C : 1111
        """;
        
String[] splitedTextBlock = splitTextBlock(textblock);
Arrays.stream(splitedTextBlock).forEach(System.out::println);
0
Freeman On

check this out:

String textblock = """
        A : 111
        B : 111
        C : 1111
        """;

String[] splitedTextBlock = textblock.split("\\R");

for (String line : splitedTextBlock) {
    System.out.println(line);
}
  • the split("\\R") method is used to split the text block by lines
  • the \\R regular expression pattern matches any line break, including different line break sequences like \n or \r\n