ToCharArray()
is a C# string method that is used to convert a string to an array of characters.
It gets a character array from a string object. When called on a string, it returns a character array.
string.ToCharArray()
// With parameters
string.ToCharArray(index, length)
The ToCharArray()
method can be used without parameters. It can also be used optionally with two parameters:
index
position to specify the characters in the string where the array conversion should start.length
to specify where it should end.An array of characters is returned.
In the code example below, we will create some strings and convert them to an array of characters using the ToCharArray()
method.
// create classclass StringToArray{// main methodstatic void Main(){// create stringsstring str1 = "Edpresso";string str2 = "Programming";// convert to array of characterschar[] a = str1.ToCharArray();char[] b = str2.ToCharArray();// // print values to consoleforeach (char ch in a){System.Console.WriteLine(ch);}System.Console.WriteLine("\n");foreach (char ch in b){System.Console.WriteLine(ch);}}}
In the code above, we created an array of characters, and we looped these arrays and printed their values to the console using foreach
.
Now, let’s limit the number of characters that make up our array using the start index
and length
.
// create classclass StringToArray{// main methodstatic void Main(){// create stringsstring str1 = "Edpresso";string str2 = "Programming";// convert to array of characterschar[] a = str1.ToCharArray(0, 3);char[] b = str2.ToCharArray(2, 4);// // print values to consoleforeach (char ch in a){System.Console.WriteLine(ch);}System.Console.WriteLine("\n");foreach (char ch in b){System.Console.WriteLine(ch);}}}
In the code above, we were able to specify where our character array should start from and where it should end using the index
and length
parameters.