Split String with Whitespace Delimiters in Java



What is split() method in Java?

The split() method of the String class accepts a delimiter (in the form of a string), divides the current String into smaller strings based on the delimiter, and returns the resulting strings as an array. If the String does not contain the specified delimiter, this method returns an array that contains only the current string.

If the String does not contain the specified delimiter, this method returns an array containing the whole string as an element.

Splitting the string with white space as delimiter

Following are steps to split a String into an array of strings with white space as delimiter:

  • Read the source string.
  • Invoke split() method by passing " " as a delimiter.
  • Print the resultant array.

Example

Following Java program reads the contents of a file into a String and splits it using the split() method with white space as delimiter:

public class SplitExample {
   public static void main(String[] args) {
      String unpiu = "Hello   how\tare\nyou doing?\nThis  is\tJava.";
      String[] result = unpiu.split("\s+");
      for (int i = 0; i < result.length; i++) {
         System.out.println(result[i]);
      }
   }
}

Output

Following is the output of the above program:

Hello
how
are
you
Updated on: 2025-05-28T18:22:12+05:30

786 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements