Last Updated : 11 Jul, 2025
In C#,
ToCharArray()is a string method. This method is used to copy the characters from a
specified stringin the current instance to a Unicode character array or the characters of a
specified substringin the current instance to a Unicode character array. This method can be overloaded by changing the number of arguments passed to it.
Syntax:public char[] ToCharArray() or public char[] ToCharArray(int startIndex, int length)Explanation:
Below are the programs to demonstrate the above Methods :
// C# program to demonstrate
// ToCharArray() method
using System;
class Geeks {
// Main Method
public static void Main()
{
String str = "GeeksForGeeks";
// copy the string str to chars
// character array & it will start
// copy from 'G' to 's', i.e.
// beginning to ending of string
char[] chars = str.ToCharArray();
Console.WriteLine("String: " + str);
Console.Write("Character array :");
// to display the resulted character array
for (int i = 0; i < chars.Length; i++)
Console.Write(" " + chars[i]);
}
}
Output:
String: GeeksForGeeks Character array : G e e k s F o r G e e k s
// C# program to demonstrate
// ToCharArray(int startIndex, int length)
// method
using System;
class Geeks {
// Main Method
public static void Main()
{
String str = "GeeksForGeeks";
// copy the string str to chars
// character array & it will
// start copy from 'F' to 'r' i.e.
// copy from startindex of string
// is 5 upto (startindex+length-1) i.e.
// 5 + (3-1) has to copy
char[] chars1 = str.ToCharArray(5, 3);
Console.WriteLine("String: " + str);
Console.WriteLine("\nCharacter array 1:");
// to display the resulted character array
for (int i = 0; i < chars1.Length; i++)
Console.WriteLine("Index " + i + " : " + chars1[i]);
// copy the string str to chars
// character array & it will
// start copy from 'F' to 'k' i.e.
// copy from startindex of string
// 5 upto (startindex+length-1) i.e.
// 5 + (7-1)
char[] chars2 = str.ToCharArray(5, 7);
Console.Write("\nCharacter array 2:");
// to display the resulted character
// array using foreach loop
foreach(char c in chars2)
Console.Write(" " + c);
}
}
Output:
String: GeeksForGeeks Character array 1: Index 0 : F Index 1 : o Index 2 : r Character array 2: F o r G e e k
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4