Split multiple lines in java

I am new to Java and trying to split multiple lines and store it in a String array. Layout Program:

Scanner sc = new Scanner(System.in); String s1 = "Hello1 Hello2"; String s2 = "Hello3 Hello4"; String s3 = "Hello5 Hello6"; String[] parts = s1.split(" "); parts = s2.split(" "); //Rewrites parts = s3.split(" "); //Rewrites for(String s4:parts) { System.out.print(s4 + " "); } 

The output of the program, obviously: Hello5 Hello6. ( How to split a string in Java )

No matter what I expect, the result is Hello1 Hello2 Hello3 Hello4 Hello5 Hello6. Which, the incoming line should not replace existing lines inside the array.

+5
source share
1 answer

Arrays are of fixed length, so all you can do is replace their existing elements or create a new separate array.

This is easier if you use a List , which can be of variable length, and use addAll to add split results to this:

 List<String> parts = new ArrayList<>(); parts.addAll(Arrays.asList(s1.split(" "))); parts.addAll(Arrays.asList(s2.split(" "))); parts.addAll(Arrays.asList(s3.split(" "))); 

Note that you should use Arrays.asList , because split returns String[] , while addAll requires a String collection, for example. List<String> .

+5
source

Source: https://habr.com/ru/post/1269548/


All Articles