-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"}
7
  • 1
    String.split(text, "\n"). Then again by ":" to get your key/value pairs. Commented Aug 3, 2023 at 15:16
  • 3
    @Jorn you probably meant text.split("\n") (or even text.split("\n", -1)) Commented Aug 3, 2023 at 15:21
  • Thanks you both, i found also that i could use text.split(System.lineSeparator()) to make it more generic Commented Aug 3, 2023 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. Commented Aug 3, 2023 at 15:22
  • 1
    alternatives: text.lines().toArray() or text.lines().toList() Commented Aug 3, 2023 at 15:23

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

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 thank you for this point, I am using it in context of unit test

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.