Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.toCharArray()

Copies the characters of a string into a new char[] array.

Available since: Java 1.0

Syntax

public char[] toCharArray()

Return value

char[]A new array of characters.

Examples

A for-each loop over the characters:

void main() {
    int digits = 0;
    for (char c : "a1b22c".toCharArray()) {
        if (Character.isDigit(c)) {
            digits++;
        }
    }
    IO.println(digits);
}

Output:

3

Sorting the letters of a word — an anagram check:

void main() {
    char[] a = "listen".toCharArray();
    char[] b = "silent".toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    IO.println(Arrays.equals(a, b));
    IO.println(new String(a));
}

Output:

true
eilnst

Notes

The array is a copy: changing it does not affect the string. Turn it back into a string with new String(array) or String.valueOf(array).

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.