
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements