OneBite.Dev - Coding blog in a bite size

split a string by empty space in java

Code snippet on how to split a string by empty space in java

  String[] words = str.split("\\s+");

This code splits a given string, str, by any continuous sequence of spaces (“\s+”) and stores the result in an array of strings, words. To break down the code, the first part is the initializing statement String[] words. This creates an empty array of strings called words. The second part is the split method. The split method takes in the string, str, and the sequence of characters which defines the delimiter, in this case, any continuous sequence of spaces. The split method will then divide the string, str, into an array of strings, which is stored in the words array that was initialized in the first part. Finally, the code will return the array of strings, words, which contains the result of the split.

java