You can use the split() method to divide a string into smaller parts. The method accepts a regular expression that defines where to split and returns an array of strings.
In this example, you will split a sentence into words using whitespace as the separator.
Source code
Save the following code as SplitStringExample.java:
public class SplitStringExample {
void main() {
String text = " Learn Java one snippet\tat a time. ";
if (text.isBlank()) {
IO.println("The text contains no words.");
return;
}
String[] words = text.strip().split("\\p{javaWhitespace}+");
for (String word : words) {
IO.println(word);
}
IO.println("Total words: " + words.length);
}
}
Explanation
The input contains spaces at both ends, multiple spaces between some words, and a tab character:
String text = " Learn Java one snippet\tat a time. ";
The escape sequence \t represents a tab.
Checking for blank text
Before splitting, the program checks whether the text is empty or contains only whitespace:
if (text.isBlank()) {
IO.println("The text contains no words.");
return;
}
This avoids treating an empty string as a word. The return statement ends the method when there is no text to process.
Removing surrounding whitespace
The strip() method removes leading and trailing whitespace:
text.strip()
It returns a string without changing the original string, because strings are immutable.
Splitting on whitespace
The following statement splits the cleaned text:
String[] words = text.strip().split("\\p{javaWhitespace}+");
The regular expression has two parts:
| Part | Meaning |
|---|---|
\p{javaWhitespace} |
Matches whitespace recognized by Character.isWhitespace() |
+ |
Matches one or more consecutive whitespace characters |
The backslash is written twice in the Java string literal so the regular expression receives a single backslash.
Using + treats consecutive spaces or tabs as one separator. This prevents empty elements between words when several whitespace characters appear together.
Reading the results
The enhanced for loop prints each element:
for (String word : words) {
IO.println(word);
}
The array’s length field gives the number of resulting words.
Run the example
Compile and run the file:
javac SplitStringExample.java
java SplitStringExample
Output
Learn
Java
one
snippet
at
a
time.
Total words: 7
This example treats each whitespace-separated token as a word. Punctuation remains attached, so the last token is "time.". For language-aware word boundaries, use a text-processing tool such as BreakIterator.
