EN
Java - split string by space character
8 points
In Java there is a couple of ways to split string by space.
xxxxxxxxxx
1
String example = "How to split string by space?";
2
3
// simple split by space char
4
String[] split1 = example.split(" ");
5
6
// split by whitespace regex - \\s
7
String[] split2 = example.split("\\s");
8
9
// split by whitespace regex once or more - \\s+
10
String[] split3 = example.split("\\s+");
Code example:
xxxxxxxxxx
1
public class JavaSplitBySpaceExample1 {
2
3
public static void main(String[] args) {
4
5
String example = "How to split string by space?";
6
String[] split = example.split(" ");
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:
xxxxxxxxxx
1
public class JavaSplitBySpaceExample2 {
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:
xxxxxxxxxx
1
public class JavaSplitBySpaceExample3 {
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?