How to convert a string to a char array and back
Short answer
toCharArray() gives an array of characters, and new String(array) or String.valueOf(array) builds the string back:
void main() {
char[] letters = "java".toCharArray();
letters[0] = 'J';
IO.println(letters.length);
IO.println(new String(letters));
}Output:
4
JavaSorting letters
With an array you can do things you cannot do with a string, like sorting. That is how anagrams are checked:
String sorted(String word) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
void main() {
IO.println(sorted("listen"));
IO.println(sorted("listen").equals(sorted("silent")));
}Output:
eilnst
trueIterating without an array
To just walk over the characters you do not need an array — use charAt() or chars():
void main() {
String word = "abc";
word.chars().forEach(c -> IO.println((char) c + " = " + c));
}Output:
a = 97
b = 98
c = 99A list of characters
Sometimes a List<Character> is more convenient:
void main() {
List<Character> chars = "hello".chars().mapToObj(c -> (char) c).toList();
IO.println(chars);
}Output:
[h, e, l, l, o]Common mistake
Printing the array via toString(). IO.println() happens to print a char[] nicely, but concatenating it with a string prints the object address:
void main() {
char[] letters = {'h', 'i'};
IO.println("Letters: " + letters);
IO.println("Letters: " + Arrays.toString(letters));
}Output:
Letters: [C@2df32bf7
Letters: [h, i]Your first line will differ — after [C@ there is a random hash code. Use Arrays.toString() or new String(letters).
Functions used in this recipe
- String.toCharArray() — Copies the characters of a string into a new char[] array.
- String.chars() — Returns a stream of the character codes of a string.
- String.valueOf() — Converts a value of any type to a string.
- String.charAt() — Returns the character at the given index.