What is ToCharArray() in C#?

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.

Syntax

string.ToCharArray()
// With parameters
string.ToCharArray(index, length)

Parameter

The ToCharArray() method can be used without parameters. It can also be used optionally with two parameters:

  • An index position to specify the characters in the string where the array conversion should start.
  • The length to specify where it should end.

Return value

An array of characters is returned.

Code

In the code example below, we will create some strings and convert them to an array of characters using the ToCharArray() method.

// create class
class StringToArray
{
// main method
static void Main()
{
// create strings
string str1 = "Edpresso";
string str2 = "Programming";
// convert to array of characters
char[] a = str1.ToCharArray();
char[] b = str2.ToCharArray();
// // print values to console
foreach (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 class
class StringToArray
{
// main method
static void Main()
{
// create strings
string str1 = "Edpresso";
string str2 = "Programming";
// convert to array of characters
char[] a = str1.ToCharArray(0, 3);
char[] b = str2.ToCharArray(2, 4);
// // print values to console
foreach (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.

Free Resources