The split method of the String class is very useful when you want to tokenize a string. Its power lies in the fact that it accepts a string, as a parameter, which can be a regular expression. However, you must be careful when you want to split a string using the whitespace character as a delimiter. Consider the following snippet of code:

String str = "Testing split using two  whitespace characters";
String[] tokens = str.split("\\s");
for(String token : tokens) {
  System.out.println("-" + token + "-");
}

What’s the output produced by the previous code? If you think it is the following, you’re wrong:

  • -Testing-
  • -split-
  • -using-
  • -two-
  • -whitespace-
  • -characters-

The actual output is:

  • -Testing-
  • -split-
  • -using-
  • -two-
  • –
  • -whitespace-
  • -characters-

Where on earth did that empty string come from? It comes from the two whitespace characters between the words two and whitespace in the str string. If this is what you want, that’s fine. However, most of the time, you will want to discard that empty string from your resulting string array. You can obtain this result by using the \s+ regex in place of \s. Basically, the previous code becomes:

String str = "Testing split using two  whitespace characters";
String[] tokens = str.split("\\s+");
for(String token : tokens) {
  System.out.println("-" + token + "-");
}