Languages
[Edit]
EN

Java - split string with more than 1 space between words

4 points
Created by:
leila
435

1. Overview

String example = "How       to split string by  space?";

// split by whitespace regex - \\s+
String[] split1 = example.split("\\s+");

// split by regex - \\s{2,8} - split string from 2 to 8 spaces
String[] split2 = example.split("\\s{2,8}");

2. Java split by whitespace regex - \\s+

Code example: 

public class JavaSplitByManySpacesExample1 {

    public static void main(String[] args) {

        String example = "How       to split string by  space?";
        String[] split = example.split("\\s+");

        System.out.println("# Original string: ");
        System.out.println(example);
        System.out.println();

        System.out.println("# Split by space string: ");
        int cnt = 1;
        for (String str : split) {
            System.out.println(cnt + " - " + str);
            cnt++;
        }
    }
}

Output:

# Original string: 
How       to split string by  space?

# Split by space string: 
1 - How
2 - to
3 - split
4 - string
5 - by
6 - space?

3. Java split by regex - \\s{2,8} - split string from 2 to 8 spaces

Code example with explanation in comment:

public class JavaSplitByManySpacesExample2 {

    public static void main(String[] args) {

        String example = "How       to split string   by  space?";

        // Regex:
        // \\s{2,8} - split string from 2 to 8 spaces
        // if there is 1 space - don't split string
        // if there is more then 8 spaces - don't split string
        //
        String[] split = example.split("\\s{2,8}");

        System.out.println("# Original string: ");
        System.out.println(example);
        System.out.println();

        System.out.println("# Split by space string: ");
        int cnt = 1;
        for (String str : split) {
            System.out.println(cnt + " - " + str);
            cnt++;
        }
    }
}

Output:

# Original string:
How       to split string   by  space?

# Split by space string:
1 - How
2 - to split string
3 - by
4 - space?

Alternative titles

  1. Java - how to split string when we have more than 1 space character between words?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - split string with more than 1 space between words

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join