Languages
[Edit]
EN

Java - how to split string when we have more then 1 space character between words?

4 points
Created by:
Kate_C
19790

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?

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join