How to convert a string to an array in Java

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(",");
System.out.println(Arrays.toString(fruits));
// [Apple, Orange, Mango, Banana]

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

String[] tokens = str2.split("\\s");
System.out.println(Arrays.toString(tokens));
// [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);
System.out.println(Arrays.toString(animals));
// [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, " ");
System.out.println(Arrays.toString(animals));
// [Fox, Dog, Loin, Tiger]

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

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.