EN
Java - split string with more than 1 space between words
4 points
xxxxxxxxxx
1
String example = "How to split string by space?";
2
3
// split by whitespace regex - \\s+
4
String[] split1 = example.split("\\s+");
5
6
// split by regex - \\s{2,8} - split string from 2 to 8 spaces
7
String[] split2 = example.split("\\s{2,8}");
Code example:
xxxxxxxxxx
1
public class JavaSplitByManySpacesExample1 {
2
3
public static void main(String[] args) {
4
5
String example = "How to split string by space?";
6
String[] split = example.split("\\s+");
7
8
System.out.println("# Original string: ");
9
System.out.println(example);
10
System.out.println();
11
12
System.out.println("# Split by space string: ");
13
int cnt = 1;
14
for (String str : split) {
15
System.out.println(cnt + " - " + str);
16
cnt++;
17
}
18
}
19
}
Output:
xxxxxxxxxx
1
# Original string:
2
How to split string by space?
3
4
# Split by space string:
5
1 - How
6
2 - to
7
3 - split
8
4 - string
9
5 - by
10
6 - space?
Code example with explanation in comment:
xxxxxxxxxx
1
public class JavaSplitByManySpacesExample2 {
2
3
public static void main(String[] args) {
4
5
String example = "How to split string by space?";
6
7
// Regex:
8
// \\s{2,8} - split string from 2 to 8 spaces
9
// if there is 1 space - don't split string
10
// if there is more then 8 spaces - don't split string
11
//
12
String[] split = example.split("\\s{2,8}");
13
14
System.out.println("# Original string: ");
15
System.out.println(example);
16
System.out.println();
17
18
System.out.println("# Split by space string: ");
19
int cnt = 1;
20
for (String str : split) {
21
System.out.println(cnt + " - " + str);
22
cnt++;
23
}
24
}
25
}
Output:
xxxxxxxxxx
1
# Original string:
2
How to split string by space?
3
4
# Split by space string:
5
1 - How
6
2 - to split string
7
3 - by
8
4 - space?