-5

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"}
  • 1
    `String.split(text, "\n")`. Then again by ":" to get your key/value pairs. – Jorn Aug 03 '23 at 15:16
  • 3
    @Jorn you probably meant `text.split("\n")` (or even `text.split("\n", -1)`) – user16320675 Aug 03 '23 at 15:21
  • Thanks you both, i found also that i could use `text.split(System.lineSeparator())` to make it more generic – Hassen Gaaya Aug 03 '23 at 15:22
  • @user16320675 Could be! Since I switched to Kotlin, I never remember what in the Java stdlib is static and what isn't. – Jorn Aug 03 '23 at 15:22
  • 1
    alternatives: `text.lines().toArray()` or `text.lines().toList()` – user16320675 Aug 03 '23 at 15:23
  • You need to be a little careful of indentation with text blocks, so you might be safer with something like `String [] splitTextBlock = textblock.lines().map(String::trim).toArray(String[]::new);` – g00se Aug 03 '23 at 16:07
  • @karl-knechtel, unfortunately, it doesn't answer how to split by line separator – Hassen Gaaya Aug 05 '23 at 14:44

2 Answers2

1

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
Freeman
  • 9,464
  • 7
  • 35
  • 58
0
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);
Yaroslavm
  • 1,762
  • 2
  • 7
  • 15
  • 1
    `System.lineSeparator()` won't work if you receive *different* line separators than what you have on the current system. For example, running the code on Linux but reading or getting some text which uses Windows line endings. Or vice versa. – VLAZ Aug 05 '23 at 15:10
  • @vlaz thank you for this point, I am using it in context of unit test – Hassen Gaaya Aug 05 '23 at 18:55