Languages
[Edit]
EN

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

4 points
Created by:
Kate_C
2854

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?

 

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍