• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

How to Split a String by Whitespaces in Java?

December 31, 2023 //  by Anees Asghar

Splitting a string means dividing the given string into smaller parts. Java allows us to split the string based on different delimiters or regex patterns, such as a “white space”, “comma”, “hyphen”, etc. In Java, strings are split using different built-in methods. Among these methods, the split() method of the Java String class is the most convenient and popular one.

Quick Outline

This write-up illustrates the following methods of splitting a string in Java:

  • What are the Whitespace Characters in Java?
  • Method 1: Split a String by Whitespaces Using String split()
  • Method 2: Split a String by Whitespaces Using StringUtils.split()
  • Method 3: Split a String by Whitespaces Using useDelimiter()
  • Method 4: Split a String by Whitespaces Using StringTokenizer

Let’s start with the String split() method.

What are the Whitespace Characters in Java?

The characters like “space”, “tab”, and “new line” are referred to as whitespace characters. In Java, these characters are represented by special symbols as illustrated below:

Whitespace CharacterSymbol | Regex
Space“ ”, “\s”, “\\s” 
Tab“\t”
New Line“\n”
All Whitespaces“\\s+”

How to Split a String by Whitespaces Using the String split() Method?

split() is an inbuilt method of the String class that splits the provided string based on the specified regex or delimiter. It doesn’t affect the actual string, instead, it retrieves a new array of split substrings. To split a string by whitespaces in Java, pass the whitespace as a delimiter/splitter to the split() method. 

Syntax

str.split(regex/delimiter, limit);

Here,

  • “str” represents a string that needs to be split.
  • regex/delimiter represents a symbol on the basis of which the provided string splits. In our case, it will be a whitespace character or a regular expression “\\s+”.
  • The “limit” is an optional parameter that determines the numbers/parts to split the string into.

Example 1: Split a String by Whitespaces “ ”

Create a string to split:

String inputString = "Hello! Welcome to javabeat.net";

Use the split() method on the inputString and pass a space character as an argument to it, such as “ ”, “\s”, “\\s”, or “\\s+”. Declare a String type array and store the split strings in it:

String[] splitString = inputString.split(" ");

Use a loop structure to Iterate over the array of split strings:

System.out.println("The Split String: ");  for (String sp : splitString) {
    System.out.println(sp);
  }

Complete Code & Output

Example 2: Split a String by Whitespaces “\\s+”, “\\s+”

Initialize a string to split and apply the “\\s” and “\\s+” on it one by one see how these delimiters work in Java:

String inputString = "Hello! Welcome   to javabeat.net";
String[] splitString = inputString.split("\\s");
String[] splitString1 = inputString.split("\\s+");

Use the for loop a couple of times to iterate and print the split strings:

System.out.println("The Split string Using \\s: ");   
    for (String sp : splitString) {
          System.out.println(sp);
}
System.out.println("The Split string Using \\s+: ");   
    for (String sp : splitString1) {
  System.out.println(sp);
}

In Java, the “\\s+” treats multiple spaces as a single delimiter so it will split the string accordingly.

Complete Code & Output

Example 3: Split a String by Tab

Pass the “\t” as a delimiter to the split() method to split a string from a tab:

String inputString = "Hello! Welcome to javabeat.net";
      String[] splitString = inputString.split("\t");
      System.out.println("Split String Using Tab: ");   
          for (String sp : splitString) {
                  System.out.println(sp);

Complete Code & Output

Example 4: Split a String by New Line

Use the “\n” as a delimiter in the split() method to split the given string from a new line:

String inputString = "Hello!\nWelcome to\njavabeat.net";

  String[] splitString = inputString.split("\n");
  System.out.println("Split String Using New Line: ");   
  for (String sp : splitString) {
      System.out.println(sp);

Complete Code & Output

Example 5: Split a String Based on User-Entered Whitespace Character

Import the Scanner class at the start of your code, in case you want to take input from the user:

import java.util.Scanner;

Initialize a string to split:

String inputString = "Hello! Welcome to \njavabeat\n.net";

Create a Scanner object, and use the next() method with that object to take a string input from the user:

System.out.println("Enter a Delimiter to Split the inputString: ");
Scanner scan = new Scanner(System.in);
String delimiter = scan.next();

Use the split() method on the input string and pass the user-entered delimiter as an argument to it:

String[] splitString = inputString.split(delimiter);

Use the for loop to iterate and print the split strings:

System.out.println("Split String: ");   
    for (String sp : splitString) {
    System.out.println(sp);    }

Complete Code & Output

Example 6: Split a String by Whitespace Using Limit Parameter

The split() method can take a Limit parameter that specifies how many parts to split the string into. In this example, we use whitespace as the separator and 3 as a limit to split the given string:

String inputString = "Welcome to javabeat.net! The best platform for Java Tutorials!";
    String [] splitString = inputString.split(" ", 3);
System.out.println("Split String: ");   
        for (String sp : splitString) {
    System.out.println(sp);
}

Complete Code & Output

Although there are multiple spaces in the given string, however, the split() method splits the given string according to the specified limit (i.e., 3).

How to Split a String by Whitespaces Using StringUtils.split() Method?

StringUtils is a built-in Java class that belongs to a third-party library “Apache Commons Lang”. This class offers a built-in “split()” method that allows us to split the given strings. It considers whitespace as its default delimiter.

To use this method, we need to create either a Maven or a Gradle project. After this, we must add the Apache Commons Lang dependency in the “pom.xml” or “build.gradle” file of a Maven or Gradle project, respectively.

In this section we create a Maven project and add the following “Apache Commons” dependencies in its “pom.xml” file”:

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.11</version>
    </dependency>
</dependencies>

Now import the StringUtils class Apache Commons lang using the following line of code:

import org.apache.commons.lang3.StringUtils;

After this create a string-type variable and initialize it with a string that you want to split:

String inputString= "Welcome to JavaBeat.net - The Best Site for Programmers";

Invoke the StringUtills.split() method on the given string to split it by space:

String[] splitString = StringUtils.split(inputString);

Finally, we use the println() method within the for loop to print the parsed string: 

System.out.println("The Split String is: ");
for (String i : splitString) {
      System.out.println(i);
}

Complete Code & Output

How to Split a String by Whitespaces Using useDelimiter()?

The useDelimiter() is a built-in method of Java’s Scanner class that splits the provided string based on the specified delimiter or pattern. To use this method, first, import the Scanner class as follows:

import java.util.Scanner;

Create a string-type variable and initialize it with the string to split:

String inputString = "Hello Welcome to JavaBeat.net";

Create an object of the Scanner class and pass the “inputString” to it as argument:

Scanner obj = new Scanner(inputString);

Apply the useDelimiter() method on the Scanner object to split the given string by space: 

obj.useDelimiter(" ");

Use the “next()” and “hasNext()” methods of the Scanner class to iterate, retrieve, and print the next tokenized string:

while (obj.hasNext()){
  System.out.println(obj.next());
}

Complete Code & Output

How to Split a String by Whitespaces Using StringTokenizer?

The StringTokenizer is an inbuilt class of the “java.util” package. In Java, the StringTokenizer() constructor is used with a target string and delimiter to split the given string:

StringTokenizer obj = new StringTokenizer(str, del);

Here, “str” is the string to split, and “del” is a delimiter based on which the given string will split.

In this section, first, we import the StringTokenizer class:

import java.util.StringTokenizer;

Next, we create a string and store it in the variable named “inputString”:

String inputString = "Hello Welcome to JavaBeat.net";

Now create an object of the stringTokenizer class using its constructor and pass the inputString along with a delimiter as its arguments:

StringTokenizer obj = new StringTokenizer(inputString, " ");

Use the while loop with the hasMoreTokens() and nextToken() methods to check if the string has more tokes, if yes, then print them:

while (obj.hasMoreTokens()){ 
  System.out.println(obj.nextToken()); 
}

Complete Code & Output

This is how you can split a string by whitespaces in Java.

Final Thoughts

To split a string by whitespaces in Java, use the split() method on the provided string and specify the whitespace as a delimiter. Alternatively, users can use the “StringUtils.split()”, “StringTokenizer()”, or “useDelimiter()” method with the whitespace as its argument. All the mentioned methods are discussed with several examples to provide a profound understanding of these methods for splitting a string by space in Java.

Category: Java

About Anees Asghar

Anees, a go-to expert of various technologies like PostgreSQL, Java, JS, and Linux. He has been contributing to the community through his words. A passion for serving the people excites him to craft primo content.

Previous Post: « How to Find the Largest Element in an Array in Java?
Next Post: String lastIndexOf() Method in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact