How do I split a string with multiple spaces?

This code snippet show you how to split string with multiple white-space characters. To split the string this way we use the "\s+" regular expression. The white-space characters include space, tab, line-feed, carriage-return, new line, form-feed.

Let’s see the code snippet below:

package org.kodejava.example.lang;

import java.util.Arrays;

public class SplitStringMultiSpaces {
    public static void main(String[] args) {
        String text = "18/08/2012    SHOES      RUNNING RED   99.9 USD";

        // Split the string using the \s+ regex to split multi spaces
        // line of text.
        String[] items = text.split("\\s+");
        System.out.println("Length = " + items.length);
        System.out.println("Items  = " + Arrays.toString(items));
    }
}

The result of the code snippet is:

Length = 6
Items  = [18/08/2017, SHOES, RUNNING, RED, 99.9, USD]

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

3 Comments

  1. But this is not working for me.

    
    if (str.contains("\\s+")) {
        var String[] strarray = str.split("\\s+")
    }
    

    Is there any alternate solution?

    Reply
    • Hi Sudheen,

      Just try the code snippet in the post to prove that it works. Why did you check if the string contains \\s+ text? Because it will simple check if your text contains that string. And also when you are using the var keyword you don’t need to define the variable type anymore.

      Reply

Leave a Reply to Dharamjeet Singh Rayat Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.