0

I'm looking for a way to convert a string to an array and strip all whitespaces in the process. Here's what I have:

        String[] splitArray = input.split(" ").trim();

But I can't figure out how to get rid of spaces in between the elements. For example,

input = " 1 2 3 4 5 "

I want splitArray to be:

[1,2,3,4,5]

MarkJ
  • 411
  • 1
  • 9
  • 23

2 Answers2

1

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:

0

Try:

String[] result = input.split(" ");
Yash
  • 3,438
  • 2
  • 17
  • 33