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.
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 the split()
method removes the delimiter from the resulting substrings. If you want to keep the delimiter, you can use the StringTokenizer
class instead.
For example:
String str = "Hello World";
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
String token = st.nextToken();
// process the token
}
This will split the string by space and keep the space character in the resulting tokens.