Splitting string on multiple spaces in java

You can use Quantifiers to specify the number of spaces you want to split on: -

    `+` - Represents 1 or more
    `*` - Represents 0 or more
    `?` - Represents 0 or 1
`{n,m}` - Represents n to m

So, \\s+ will split your string on one or more spaces

String[] words = yourString.split("\\s+");

Also, if you want to specify some specific numbers you can give your range between {}:

yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces

str.split("\\s+") would work. The + at the end of the regular-expression, would treat multiple spaces the same as a single space. It returns an array of strings (String[]) without any " " results.


Use a regular expression.

String[] words = str.split("\\s+");

Tags:

Java

String

Split