Java - Split String by Space
In Java, to split a string by spaces, we can use the split()
method of the
String
class, StringTokenizer
, or Java 8 Streams. In this article, we will learn the usage of these methods with examples to split the string by spaces in Java.
Example: The simplest and most commonly used way to split a string by spaces is by using the split()
method of the String
class.
// Java Program to Split a String by Space
public class SplitString {
public static void main(String[] args) {
String s = "Java is a Programming Language.";
String[] w = s.split(" "); // Split by space
for (String word : w) {
System.out.println(word);
}
}
}
Output
Java is a Programming Language.
Other Methods to Split a String by Space
1. Using split()
with Multiple Spaces
If the string contains multiple spaces between words, we can handle it with a regular expression.
// Java Program to Split a String by Space
public class SplitByString {
public static void main(String[] args) {
String s = "Java is a Programming Language.";
String[] w = s.split("\\s+"); // Split by one or more spaces
for (String word : w) {
System.out.println(word);
}
}
}
Output
Java is a Programming Language.
Explanation:
In the above example, the
split("\\s+")
matches one or more whitespace characters, including spaces, tabs, and newlines.
2. Using StringTokenizer
We can use the StringTokenizer
class for splitting strings into tokens based on a delimiter, such as a space. This method is considered outdated but still works.
// Java Program to Split a String by Space
// using StringTokenizer
import java.util.StringTokenizer;
public class SplitString {
public static void main(String[] args) {
String s = "Java is a programming language";
StringTokenizer t = new StringTokenizer(s, " "); // Tokenize by space
while (t.hasMoreTokens()) {
System.out.println(t.nextToken());
}
}
}
Output
Java is a programming language
Explanation: In the above example, the StringTokenizer
splits the string into tokens based on the space character. The hasMoreTokens()
method checks if there are more tokens, and nextToken()
returns the next word.
3. Using Streams (Java 8+)
In Java 8, we can use the Streams for a more functional approach, especially if we need additional processing.
// Java Program to Split a String by Space
// using Streams
import java.util.Arrays;
public class SplitString {
public static void main(String[] args) {
String s = "Java is a programming language";
// Use Stream to split and process the words
Arrays.stream(s.split(" ")) // Split the string by space
.forEach(System.out::println);
}
}
Output
Java is a programming language
Explanation:In the above example, the split(" ")
method splits the string into words, and Arrays.stream()
converts the array to a stream. The forEach()
method is used to print each word in the stream.