JavaDevNotes.com

Java String To Char Array

String is just a staple of most programming languages. It represents a sequence of characters into one data structure. It is a very convenient way to store many types of things in memory or in the database. An array on the other hand is one of the most simple way to represent multiple values. It is simpler that Classes such as List or Set because it can also be found in older programming language such as C/C++ or Pascal. It is only natural that we sometimes want to convert a String into an array of Characters for easier manipulation later. Below are some ways on how we can Convert a String to Char Array in Java .

Convert String To Char Array Using toCharArray()

Fortunately, the String class has a built in function toCharArray() that can do this conversion for us. Here is the signature.
public char[] toCharArray()
The Java documentation says that this function Converts this string to a new character array.. Further it states that it returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. Consider the code below that uses this function.
String myString = "Math";
char[] charArray = myString.toCharArray();

We can even use this in String literal, because String literals are actually String instances.

char[] charArray = "Science".toCharArray();

To complete our example, try to guess the output of below code:
public class Test {
    public static void main(String[] args) {
        String myString = "Dog";
        char[] charArray = myString.toCharArray();
        System.out.println(charArray[0]);
        System.out.println(charArray[1]);
        System.out.println(charArray[2]);
    }
}

We get an array with size 3 having the first item as "D", the second as "o", and the third as "g". The output should be:

D
o
g

Convert String To Char Array Using Java 8 String.chars()

There are cool ways that we could solve this problem if we are using Java 8. Here is an example on how to convert using Java 8 and String's chars() method.
public class Test {
    public static void main(String[] args) {
        String myString = "Hi";
        Character[] charArray = myString.chars().mapToObj(x -> (char) x).toArray(Character[]::new);
        System.out.println(charArray[0]);
        System.out.println(charArray[1]);
    }
}
This one does a lot of things in one go. But we still get an array of character in the end, which is what we want. The output would be:
H
i

If we look at the signature of chas() in Java documentation we will get:

public default IntStream chars();

It says that this returns a stream of int zero-extending thechar values from the sequence.

Convert String To Char Array Using Java 8 String.codePoints()

Another alternative in Java 8 is to use codePoints instead of chars() method. Everything else is similar:
public class Test {
    public static void main(String[] args) {
        String myString = "Ho";
        Character[] charArray = myString.codePoints().mapToObj(x -> (char) x).toArray(Character[]::new);
        System.out.println(charArray[0]);
        System.out.println(charArray[1]);
    }
}
The output should be the expected display:
H
o

If we look at the signature of codePoints() in Java documentation we will get:

public default IntStream codePoints();

It says that this returns a stream of code point values from the sequence.

Convert String To Char Array Using Own Code

Just to exercise our brain, we can also implement our own solution to convert a String to an array of Character. See below code:

public static char[] ourToCharArrayFunction(String str) {
    char[] result = new char[str.length()];
    for (int i=0; i<str.length(); i++) {
        result[i] = str.charAt(i);
    }
    return result;
}

The first line is we created an array with size the same length as the String.
char[] result = new char[str.length()];

Then we copy each character from the String to the corresponding array element.

for (int i=0; i<str.length(); i++) {
    result[i] = str.charAt(i);
}
Putting it all together in an example, we have:
public class Test {
    public static char[] ourToCharArrayFunction(String str) {
        char[] result = new char[str.length()];
        for (int i=0; i<str.length(); i++) {
            result[i] = str.charAt(i);
        }
        return result;
    }
    public static void main(String[] args) {
        char[] charArray = ourToCharArrayFunction("Apple");
        System.out.println(charArray[0]);
        System.out.println(charArray[1]);
        System.out.println(charArray[2]);
        System.out.println(charArray[3]);
        System.out.println(charArray[4]);
    }
}

We use the function and pass the String "Apple" and we will have the following output:
A
p
p
l
e