2.4. Splitting a String
Problem
You want to split a string on a number of different character delimiters.
Solution
Use StringUtils.split()
, and supply a series of characters to split
upon. The following example demonstrates splitting strings of a comma
and a space:
import org.apache.commons.lang.ArrayUtils; String input = "Frantically oblong"; String input2 = "Pharmacy, basketball,funky"; String[] array1 = StringUtils.split( input, " ,", 2 ); String[] array2 = StringUtils.split( input2, " ,", 2 ); System.out.println( ArrayUtils.toString( array1 ) ); System.out.println( ArrayUtils.toString( array2 ) );
This produces the output:
{ "Frantically", "oblong" }
{ "Pharmacy", "basketball" }Discussion
The StringUtils.split( ) function does not return
empty strings for adjacent delimiters. A number of different
delimiters can be specified by passing in a string with a space and a
comma. This last example limited the number of tokens returned by
split with a third parameter to StringUtils.split(). The input2 variable contains three
possible tokens, but the split function only returns an array of two
elements.
The most recent version of J2SE 1.4 has a String.split() method, but the lack of split( ) in
previous versions was an annoyance. To split a string in the old
days, one had to instantiate a StringTokenizer,
and iterate through an Enumeration to get the
components of a delimited string. Anyone who has programmed in Perl
and then had to use the StringTokenizer class will tell you that programming ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access