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:
3Sorting 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
eilnstNotes
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
- String.chars() — Returns a stream of the character codes of a string.
- String.charAt() — Returns the character at the given index.
- String.valueOf() — Converts a value of any type to a string.
- Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
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.