One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Showing posts with label split. Show all posts
Showing posts with label split. Show all posts

Monday, December 31, 2018

How to split a String by space (any white space)

The String splitting is a very common requirement in any programming language. In java it is very much straight forward since there is a split() method in String. Normally what we do is provide the delimiter to the split method and get the tokens into a String array.

But most of beginners don't know we can pass regular expression as a delimiter.

Here I am using a regular expression as a delimiter to split the String by any white space regardless it is a tab, space, multiple tabs or spaces.

str = "This is     the String with    different white spaces";
String[] splited = str.split("\\s+");