Java – Split a String with Space as Delimiter

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

The syntax to split string by space is

</>
Copy
String.split(" ")

In the following program, we have taken a string and split it by space.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args){
		String str = "abc defg hi jklm";
		String parts[] = str.split(" ");
		for(String part: parts) {
			System.out.println(part);
		}
	}
}

Output

abc
defg
hi
jklm

If we would like to split the string by one or more whitespace characters, we can use the regular expression "\\s+" as shown in the following syntax.

</>
Copy
String.split("\\s+")

In the following program, we have taken a string and split it by one or multiple spaces.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args){
		String str = "abc \t defg hi   jklm";
		String parts[] = str.split("\\s+");
		for(String part: parts) {
			System.out.println(part);
		}
	}
}

Output

abc
defg
hi
jklm

Conclusion

In this Java Tutorial, we learned how to split a string by space, using String.split() method.