by Sai gowtham

How to split a String by Space in Java

To split a string by space, we can use the String.split() method by passing a regex \\s+ as an first argument in Java.

Here is an example.

import java.util.Arrays;

public class Main
{
	public static void main(String[] args) {
	    String str = "You can see me";
        String[] splited = str.split("\\s+");
		System.out.println(Arrays.toString(splited));
	}
}

Output:

[You, can, see, me]

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course