3

I'm new to Java and trying to split multiple strings and store it in a String array. The layman program follows:

    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 ouput of the program is obviously : Hello5 Hello6. (How to split a string in Java)

Regardless I expect the output Hello1 Hello2 Hello3 Hello4 Hello5 Hello6. Which is, the incoming string must not replace the existing Strings inside the array.

DeathJack
  • 595
  • 1
  • 6
  • 26

1 Answers1

5

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

It is easier if you use a List, which can be variable-length, and use addAll to add the results of the split to that:

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 have to use Arrays.asList here because split returns a String[], whereas addAll requires a collection of String, e.g. List<String>.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243