Posts

Showing posts with the label Split a whitespace separated String

Split a String in Java - 5 different ways

Image
In this section, we will show you five different ways to split a String in Java based on  the delimiter. 1. Using  String.split() The split method in Java splits a string into substrings using a delimiter that is specified using a regular expression. 1. This method returns an array of strings. 2. This method takes a regex string as a parameter. Split a whitespace separated String //Split by a whitespace String input = "yellow black green orange" ; String [] colors = input .split( " " ); Split a comma separated String //Split by a comma String input = "yellow,black,green,orange" ; String [] colors = input .split( " , " ); Split a dot separated String //Split by a dot String input = "123.12.12.1" ; String [] splitted = input .split( " \\ . " ); Split and Trim a comma separated String String input = " yellow,black ,green, orange" ; String [] colors = input .trim().split( " \\ s*, \\ s* " ); trim() method rem