In an earlier article, we discussed different ways to convert an array to a string in Java. Today, you'll learn to convert a string into an array that contains subsets of input string split by a delimiter.

Convert a string to an array using String.split()

The most common way to split a string into an array in Java is the String.split() method.

This method returns a string array by splitting the string using the specified delimiter. The separator can be a string or a regular expression.

Here is an example:

// String as a delimiter
String str = "Apple,Orange,Mango,Banana";

String[] fruits = str.split(",");
// [Apple, Orange, Mango, Banana]

// Regular expression as the delimiter
String str2 = "Java is awesome 🌟";

String[] tokens = str2.split("\\s");
// [Java, is, awesome, 🌟]

Convert a string to an array using Pattern.split()

The Pattern class defines a regular expression for searching and replacing texts.

First, you need to call the Pattern.compile() method to create a pattern. It accepts two parameters: a regular expression string and a flag indicating whether the search is case-insensitive or not.

Next, the split() method is used to split the string into an array according to the specified pattern defined in the first step:

String str = "Fox Dog Loin Tiger";
Pattern pattern = Pattern.compile("\\s");

String[] animals = pattern.split(str);
// [Fox, Dog, Loin, Tiger]

Convert a string to an array using Apache Commons Lang

Finally, the last way to convert a string into an array is the Apache Commons Lang library. The split() method of the StringUtils class from Commons Lang transforms a string into an array of strings:

String str = "Fox Dog Loin Tiger";

String[] animals = StringUtils.split(str, " ");
// [Fox, Dog, Loin, Tiger]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.