Java String Handling RegEx

Convert String to String array in Java example

Convert String to String array in Java example shows how to convert String to String array in Java. Example also shows how to convert comma separated String to String array using split method and regular expression.

How to convert String to String array in Java?

Consider below given String object which you want to convert to String array such that each element of an array will contain one word of the String.

You can do that by using split method of String class as given below.

Output

How to convert comma separated String to String array?

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

Output

How to convert String to String array containing each characters of the String?

There are a couple of ways using which you can convert String to String array containing each characters of the String as an element of the array

1. Using charAt and valueOf methods of String class

Loop through the characters of the String and convert each character to String using charAt and valueOf methods of String class as given below.

Output

2. Using Regular Expression

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

Output

Important Note:

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

If you are using Java 7 or lower version, you can use “(?!^)” 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

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

 

Join 1000+ fellow learners! Enter your email address below: