C# String ToCharArray()

The ToCharArray() method copies the characters in the string to a character array.

Example

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      char[] result;

// copies str to result result = str.ToCharArray();
// prints result for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + ", "); } Console.ReadLine(); } } } // Output: I, c, e, c, r, e, a, m,

ToCharArray() Syntax

The syntax of the string ToCharArray() method is:

ToCharArray(int startIndex, int length)

Here, ToCharArray() is a method of class String.


ToCharArray() Parameters

The ToCharArray() method takes the following parameters:

  • startIndex - starting position of a substring in the string
  • length - length of the substring in the string

ToCharArray() Return Value

  • returns a char array

Example 1: C# String ToCharArray()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Chocolate";
      char[] result;

// copies str to result result = str.ToCharArray();
// prints result for (int i = 0; i < result.Length; i++) { Console.WriteLine(result[i]); } Console.ReadLine(); } } }

Output

C
h
o
c
o
l
a
t
e

Example 2: C# String ToCharArray() With Parameters

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      char[] result;

// copies 4 chars from index 3 of str result = str.ToCharArray(3, 4);
// prints result for (int i = 0; i < result.Length; i++) { Console.WriteLine(result[i]); } Console.ReadLine(); } } }

Output

c
r
e
a

Notice the code,

str.ToCharArray(3, 4) 

Here,

  • 3 - starting index to copy characters from
  • 4 - length of the string to be copied
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges