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