Search code examples
javasplittokenize

Java String split method split by 2 or more spaces


How can I split a string by "2 or more spaces" only using the java split method

An example:

"cat dog    horse   elephant"

will be splitted into:

cat dog
horse
elephant

Thanks.


Solution

  • You need to split the String using following regex

    \\s{2,}
    

    This will split the string by 2 or more spaces

    String str = "cat dog    horse   elephant";
    String[] parts = str.split("\\s{2,}");