Split a String into Words in Java

This Java tutorial shows how to split a string into multiple words.

In Java 1.4, Sun added a split() method to the String class. The split method allows you to specify a regular expression that is used to split the string into a string array. To split a string where there words are separated by a space, simply specify a space (" ") as the parameter to the split() method.

The following code example shows how to split a sentence into words:

String sentence = "This is a sentence.";
String[] words = sentence.split(" ");

for (String word : words)
{
System.out.println(word);
}
Below is output from the example code:
This
is
a
sentence.


8 comments:

Juan said...

Good code.

I was looking for something that save the tokens in new string.

For example you have the String "Hello Beauty World"

Save in a String1 = Hello"
String2 = "Beauty", etc.

You know how can i do this??

Thanks. And Sorry for my bad english.

Anonymous said...

they are saved in the string array the split() method returns.
the way to access it:

String sentence = "This is a sentence.";
String[] words = sentence.split(" ");

for (int i = 0; i < words.length; i++) {
System.out.println(word[i]);
}

Anonymous said...

Anonymous said:
"for (int i = 0; i < words.length; i++) {
System.out.println(word[i]);
}"

Add an 's' to `word` in the print line.

Dragon said...

what if the sentence is
" A very good day"

the program wont work

Gizmo said...

You could call the string trim() method to remove the leading and trailing white space.

Pavan said...

Hi,
It was good code when the split character is single like "space" but when we have encounter multiple split pattern and some pattern are combination of two or more pattern then what procedure we have to call.

Thanks

Anonymous said...

Here is problem:

String line = " Bada Bing, Bada Boom ";
String[] words = line.split(" ");
for (int i = 0; i < words.length; ++i) {
System.out.println(i + words[i]);
}

Output:
--------
0
1 Bada
2 Bing,
3 Bada
4 Boom
--------
So, using split we have an extra empty element right at the top of the array.

Kevin said...

You can use the trim() method on the string first to remove the leading and trailing spaces.

Post a Comment