W3docs

How to split a String by space

In Java, you can split a string by space using the split() method of the String class. This method takes a regular expression as an argument and returns an array of substrings split by the regular expression.

In Java, you can split a string by space using the split() method of the String class. This method takes a regular expression as an argument (note that special regex characters must be escaped) and returns an array of substrings split by the regular expression.

To split a string by space, you can use the regular expression \\s+, which matches one or more whitespace characters.

For example:


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

The words array will contain the following elements:


words[0] = "Hello";
words[1] = "World";

You can also use the String.split() method with a space character as the delimiter:


String str = "Hello World";
String[] words = str.split(" ");

This will also split the string by space. Note that split(" ") treats each space as a separate delimiter, which can produce empty strings for consecutive spaces, whereas split("\\s+") groups them.

Note that the split() method removes the delimiter from the resulting substrings. Both split() and StringTokenizer discard the delimiter from the resulting tokens.

For example:


String str = "Hello World";
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
  String token = st.nextToken();
  // process the token
}

This will iterate over the space-separated tokens.

Note that split() discards trailing empty strings by default; use split(regex, -1) to preserve them.