Skip to content

Convert String to String array in Java example

This example shows how to convert string to string array in Java as well as how to convert comma separated string to string array using the split method and regular expression.

How to convert String to a String array in Java?

We want to convert the string to an array of strings such that each element of an array will contain one word of the string. You can do that by using the split method of the String class as given below.

Output

How to convert comma separated string to string array?

If the string contains comma separated values which you want to convert such that each value becomes an element of the array, use below given code.

Output

How to convert array containing each character of the string?

1. Using the charAt and valueOf methods of the String class

We will loop through the characters of the string and convert each character to string using the charAt and valueOf methods as given below.

Output

2. Using a Regular Expression

Use the regular expression along with the split method of the String class to split string by empty strings as given below.

Output

Important Note:

You may have noticed from the output that the first element of an array is a blank or empty string. This problem is applicable up to Java 7. However, If you are using Java 8 or a later version, the first element returned from split method is no longer empty String.

If you are using Java 7 or lower version, you can use the “(?!^)” pattern instead which gives the correct result, where

When used along with the split method, the regular expression pattern “(?!^)” means that split all the characters of the string except for the start of the string (i.e. first character of the String).

Output

This example is a part of the String in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.