Sometimes, we need to convert a string to array in Java based on some criteria to address one problem or another. Unfortunately, Java does not provide any direct way to accomplish this automatically!

So, in this tutorial, we will try to cover in depth the most commonly used methods to convert a string into an array of characters. You can also check how to convert array to string!

Let’s get started.

Split String into an Array in Java

There are many options out there that you can use to tackle string to array conversion. We will walk you through from beginning to end so you can implement each method without getting confused.

String split() Method

Split method belongs to String class and it is mainly used to turn a simple string into a new array! It returns an array of string by splitting a string using a delimiter of your choice. The separator can be a string or a regular expression.

Let’s discover together how we can use split method to convert a simple string to array:

    
        package com.azhwani
        public class StringToArray {
            public StringToArray() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String str = "Hello;string;into;array;conversion;tutorial";
                // Split our String using ; separator 
                String[] strarray = str.split(";");
                if(strarray.length > 0){
                    for(String elm: strarray){
                        System.out.print(elm+" ");
                    }
                }
                else{
                    System.out.println("No elements to display!");
                }
                System.out.println("");
                // Split string using regular expression
                String str2 = "Hi buddy! Smile, sunshine is good for your teeth";
                String[] strarray2 = str2.split("\\s");
                if(strarray2.length > 0){
                    for(String elm: strarray2){
                        System.out.print(elm+" ");
                    }
                }
                else{
                    System.out.println("No elements to display!");
                }
            }
        }
        // Example's output
        Hello string into array conversion 
        Smile, sunshine is good for your teeth 
    

Using Pattern.split()

This split() method is defined in Pattern class and it is used to break a given string passed as parameter into an array according to a given pattern defined using compile method!

This example will show how to use split() and compile() methods to turn a given string to array using regular expression as delimiter:

    
        import java.util.regex.Pattern;
        public class StringToArrayPattern {
            public StringToArrayPattern() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String mystr = "Turn Text Into Java Array Example";
                // Define our REGEX
                String PATTERN = "\\s"; 
                // Create a pattern using compile method
                Pattern pattern = Pattern.compile(PATTERN); 
                // Create an array of strings using the pattern we already defined
                String[] strtoarray = pattern.split(mystr); 
                // Print our array
                for (int i = 0; i < strtoarray.length; i++) { 
                    System.out.println("strtoarray[" + i + "]=" + strtoarray[i]); 
                } 
            }
        }
        // Output
        strtoarray[0]=Turn
        strtoarray[1]=Text
        strtoarray[2]=To
        strtoarray[3]=Java
        strtoarray[4]=Array
        strtoarray[5]=Example
    

Split Method of StringUtils

StringUtils is an utility class provided by Apache Commons project! This class offers multiple null-safe methods related to String handling! It is a good alternative since java.lang.String cannot handle all String related operations!

To use StringUtils class, you need to import the commons-lang3 JAR file into your project. You can download it and import it manually or you can just use a dependency management tool like Maven or Gradle.

You can download the latest version of Apache Commons Lang 3 from here

StringUtils class provide split method which can be used to convert string to array in Java:

    
        import org.apache.commons.lang3.StringUtils;
        public class StringToArrayStringUtils {
            public StringToArrayStringUtils() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String mystr = "Just#Trying#To#Test#StringUtils#Split#Method";
                String [] splitedarray = StringUtils.split(mystr, "#");
                for(int i=0; i< splitedarray.length; i++ ) {
                    System.out.println( i + ") "+ splitedarray[i]);
                }
            }
        }
    

Use stringUtils to split string to array

Using StringTokenizer Class

StringTokenizer is a legacy class that belong to java.util package, it allows us to break or split a string into small parts called tokens with the help of delimiters.

The process of breaking a string into multiple tokens is called String tokenization! Space is the default delimiter used for breaking the string into tokens!

Let’s see a simple example of how to use StringTokenizer class to tokenize a given string in Java.

    
        import java.util.StringTokenizer;
        public class StringToArrayStringUtils {
            public StringToArrayStringUtils() { 
            }
            public static void  main(String[] args) {
                String str = "Just, trying to understand, StringTokenizer class, with an example";
                // Tokenize a given string using the default delimiter
                StringTokenizer tokenizer1 = new StringTokenizer(str);
                String [] strarray1 = new String[tokenizer1.countTokens()];
                // Add tokens to our array 
                int i = 0;
                while(tokenizer1.hasMoreTokens()) {
                    strarray1[i] = tokenizer1.nextToken();
                    i++;
                }
                for(String stritem : strarray1){
                    System.out.println(stritem);
                }
                System.out.println("----------------------------");
                // Break a given string into tokens using , delimiter
                StringTokenizer tokenizer2 = new StringTokenizer( str,",");
                String [] strarray2 = new String[tokenizer2.countTokens()];
                i = 0;
                while(tokenizer2.hasMoreTokens()) {
                    strarray2[i] = tokenizer2.nextToken();
                    i++;
                } 
                for(String stritem : strarray2){
                    System.out.println(stritem);
                }
            }
        }
        // Output
        Just,
        trying
        to
        understand,
        StringTokenizer
        class,
        with
        an
        example
        ----------------------------
        Just
         trying to understand
         StringTokenizer class
         with an example
    

Using Guava Library

Guava is a Java-based library developed by Google! It provides some great mechanisms and utilities for joining and splitting strings.

To use Guava library, you need to add it in your Java project, if you are using Maven, include Guava dependency into your POM file!

If you are not a big fan of dependencies management tool like Maven, then you have to follow these steps:

  • Download Google Guava JAR.

  • Import the JAR into your project.

  • Add JAR file as a library.

Guava’s Splitter class provides an interesting method splitToList() to turn a String into a collection of elements using some delimiter. The separator can be specified as a single character, fixed string or a regex pattern!

Unlike other classes, Splitter provides a more object orientated way to split a string to array in Java! It can also trim white space *trimResults()** and skip empty elements omitEmptyStrings() for you to get clean result!

In the following example, we split a String into a List using the “#” as a separator:

    
        import com.google.common.base.Splitter;
        import java.util.List;
        public class StringToArrayGuava {
            public StringToArrayGuava() { 
            }
            public static void  main(String[] args) {
                String mystr = "Guava# is # # From Google! You can use it# to split Strings in Java";
                // Create a splitter object, which you then use to do the splitting!
                // trimResults() : Trim the result
                // omitEmptyStrings() : Ignore empty elements
                Splitter mySplitter = Splitter.on('#')
                                              .trimResults()
                                              .omitEmptyStrings();
                // Split string to List 
                List<String> strList = mySplitter.splitToList(mystr); 
                // Convert List to Array
                String[] myarray = strList.toArray(new String[strList.size()]);
                for (String item : myarray) { 
                    System.out.println(item); 
                } 
            }
        }
        // Output
        Guava
        is
        From Google! You can use it
        to split Strings in Java
    

How to Convert String to char Array Java ?

Java provides multiple ways to convert a string into an array of characters. It is apt to you to choose which one you can use depending on your needs!

Let’s get an up-close look at some of the available methods.

Using toCharArray() Method

This method of String class returns an array of characters from a given string. The returned array has the same length as the length of the string.

The following example shows how to convert a string to char array using toCharArray() method.

    
        public class StringToCharArray {
            public StringToCharArray() { 
            }
            public static void  main(String[] args) {
                // convert String to character array
                String str = "toCharArray";
                char chararray[] = str.toCharArray();
                for(char ch:chararray){
                    System.out.println(ch);
                }
            }
        }
    

How to convert string to char array

Using getChars()

public void getChars(int start, int end, char[] arr, int arrstart) is used to copy characters from a given string into an array.

  • start : Index of the first character of the string to copy.

  • end : Index after the last character to copy.

  • arr : Destination array where chars will be copied.

  • arrstart : The first index in array where the first character will be pushed.

    
        public class GetCharsExample {
            public GetCharsExample() { 
            }
            public static void  main(String[] args) {
                String mystr = "Testing getChars method";
                char[] chararr = new char[8];
                // copying string to char array
                mystr.getChars(8, 16, chararr, 0);
                for(char ch: chararr){
                   System.out.print(ch+" ");
                }
            }
        }
        // Output
        g e t C h a r s
    

Java 8 chars() Method

chars() is a new method introduced by String API in Java 8! It can be used to create an instance of Stream from a String object! You can use mapToObj() and toArray() methods with chars() method to convert string to char array.

    
        public class Java8Chars {
            public Java8Chars() { 
            }
            public static void  main(String[] args) {
                String mystr = "Java 8 Chars";
                // Create character array from string
                Character[] arraychars = mystr.chars()
                                              .mapToObj(c -> (char) c)
                                              .toArray(Character[]::new);
                for(Character ch: arraychars){
                    if(Character.isLowerCase(ch))
                        System.out.print(ch+" ");
                }
                System.out.println("");
                "hi java 8 chars".chars().forEach(c -> System.out.print((char)c+" "));
            }
        }
        // Output
        a v a h a r s 
        h i   j a v a   8   c h a r s
    

How do I Turn a List of Strings to Array ?

As a Java developer you may encounter a case where you need to turn a List to an Array! Well, conversion between List and Array is a very common operation. I will try to discuss in this chapter, how to convert a List of strings into a Java array.

Convert String to Array Using toArray(T[])

toArray() is a method provided by List interface and it is by far the easiest way to convert a List to an Array in Java! It returns an array containing all of the elements of the list!

The example below shows how to convert a List of string to an Array using toArray method:

    
        import java.util.ArrayList;
        public class ToArrayExample {
            public ToArrayExample() { 
            }
            public static void  main(String[] args) {
                // create a List of string
                ArrayList<String> strlist = new ArrayList<String>();
                strlist.add("Hello");
                strlist.add("ToArray");
                strlist.add("Method"); 
                // toArray copies list elements into an array
                String strarray[] = new String[strlist.size()];
                strarray = strlist.toArray(strarray);
                for (String str : strarray) {
                    System.out.println("String = " + str);
                }
            }
        }
    

Java 8 Stream

Stream is a new concept introduced in Java 8! It represents a sequence of objects from a source which can be pipelined to produce a desired result! The source simply provides data to a Stream and it can be a Collection or an Array …!

Stream API provides one of the simplest ways to convert a Stream of string into array of string! All, you need to do is to use Stream.toArray() method!

In the above example, we create a stream from a list of string using stream() method and then turn the stream into a new array using toArray().

    
        import java.util.ArrayList;
        import java.util.stream.Stream;
        public class StreamToArrayExample {
            public StreamToArrayExample() { 
            }
            public static void  main(String[] args) {
                // Create a List of string
                ArrayList<String> mylist = new ArrayList<String>();
                mylist.add("Testing");
                mylist.add("Java8");
                mylist.add("Stream"); 
                mylist.add("API"); 
                // Create a stream of string from our list
                Stream<String> mystream = mylist.stream();
                // Convert the stream into an array of string
                String[] strarr = mystream.toArray(String[]::new);
                for (String stri : strarr) {
                    System.out.println("String = " + stri);
                }
            }
        }
    

Java 8 stream to array

Using Traditional Loop

The most basic way to convert a List of string to Array in Java is to use looping concept! You can iterate over the list and push each element into the array!

    
        import java.util.ArrayList;
        public class ListToArrayExample {
            public ListToArrayExample() { 
            }
            public static void  main(String[] args) {
                // create a List of string
                ArrayList<String> nameslist = new ArrayList<String>();
                nameslist.add("Linda");
                nameslist.add("John");
                nameslist.add("Karin"); 
                nameslist.add("Azhwani"); 
                nameslist.add("Isabella");
                nameslist.add("Lucas");
                // Using iterator interface
                String namesarray[] = new String[nameslist.size()];
                Iterator<String> namesIterator = nameslist.iterator();
                int index = 0;
                while (namesIterator.hasNext()) {
                    namesarray[index] = namesIterator.next();
                    index++;
                }
                for (String stri : namesarray) {
                    System.out.println(stri);
                }
                String namesarray2[] = new String[nameslist.size()];
                // Using For loop
                for (int i = 0; i < nameslist.size(); i++) {
                    namesarray2[i] = nameslist.get(i);
                }
                for (String stri : namesarray2) {
                    System.out.println(stri);
                }
            }
        }
    

Conclusion:

In this article, you learned how to convert string to array in Java. You learned also different ways of splitting simple string to char array.

Thanks for reading. Have a nice day!