First off, this input.split(" ").trim();
won't compile since you can't call trim()
on an array, but fortunately you don't need to. Your problem is that your regex, " "
is treating each space as a split target, and with an input String like so:
String input = " 1 2 3 4 5 ";
You end up creating an array filled with several empty ""
String items.
So this code:
String input = " 1 2 3 4 5 ";
// String[] splitArray = input.split("\\s+").trim();
String[] splitArray = input.trim().split(" ");
System.out.println(Arrays.toString(splitArray));
will result in this output:
[1, , , , , , , , 2, 3, 4, , , , , , 5]
What you need to do is to create a regex that greedily groups all the spaces or whitespace characters together, and fortunately we have this ability -- the +
operator
Simply use a greedy split with the whitespace regex group
String[] splitArray = input.trim().split("\\s+");
\\s
denotes any white-space character, and the trailing +
will greedily aggregate one or more contiguous white-space characters together.
And actually, in your situation where the whitespace is nothing but multiples of spaces: " "
, this is adequate:
String[] splitArray = input.trim().split(" +");
Appropriate tutorials for this: