How to split a string by space in Java

In this tutorial, we will learn how to split a string by space in Java. This can be done using the Java string split() method.

Split a string by space in Java

The split method takes a parameter which is a regular expression and returns an array of strings. You can use the following syntax:

arrayReferenceVar = StringVar.split(Regex);

To split the string based on whitespace, the regular expression will be “\\s”.

Example

The following example shows how to split a string based on whitespace.

public class StringSplit {
  public static void main(String Args[]) {
    String s = "CodeSpeedy Technology Private Limited";
    //Declaring an array of strings to store the result after splitting the string
    String[] sWords;
    System.out.println("Before splitting: "+s);
    //splitting the string based on whitespace
    sWords = s.split("\\s");
    //printing the result
    System.out.println("Result after splitting:");
    for(int i=0; i<sWords.length; i++) {
      System.out.println(sWords[i]);
    }
  }
}

Output

The output of the code is:

Before splitting: CodeSpeedy Technology Private Limited
Result after splitting:
CodeSpeedy
Technology
Private
Limited

Here is a tutorial you can check out next: How to convert string to int in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *