![]() |
VOOZH | about |
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 is a Programming Language.
split() with Multiple SpacesIf the string contains multiple spaces between words, we can handle it with a regular expression.
Java is a Programming Language.
Explanation: In the above example, the split("\\s+") matches one or more whitespace characters, including spaces, tabs, and newlines.
StringTokenizerWe 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 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.
In Java 8, we can use the Streams for a more functional approach, especially if we need additional processing.
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.