ToCharArray
Consider a string
: it is immutable and cannot be changed. But an array can be changed. With toCharArray
we get a char
array from a string
.
With this method, we change a string
into a mutable form. We can modify letters in the array. Then we convert it back into a String
.
Here we begin with a String
that contains the letters "abc." Then we call toCharArray
on it. We print this array with Arrays.toString
.
Arrays.toString
.char
array to a string
with "new String." This invokes the String
constructor.import java.util.Arrays; public class Program { public static void main(String[] args) { String letters = "abc"; // Convert String to a char array. char[] array = letters.toCharArray(); System.out.println(Arrays.toString(array)); // Modify the array. array[0] = 'A'; System.out.println(Arrays.toString(array)); // Get the String. String result = new String(array); System.out.println(result); } }[a, b, c] [A, b, c] Abc
toCharArray
Some string
manipulations are not simple. We cannot just use insert()
or replace()
for all things. With toCharArray
we can change characters.
Code that uses toCharArray
can be hard to read. For this reason, placing it in a method can be helpful. These methods can receive a String
and return a modified one.
With toCharArray
we have a built-in way to get characters from a String
. We do not need to get characters in a loop—we can get them all at once from a Java method.