C# String - ToCharArray() Method



The C# String ToCharArray() method converts a string into a character array (char[]). The converted character array contains all the characters of the string.

Syntax

Following are the syntax of the C# string ToCharArray() method −

Default Syntax −

Converts the entire string into a character array −

public char[] ToCharArray();

Syntax with both startIndex and length −

Converts a substring of string to a character array starting from startIndex to length characters.

public char[] ToCharArray(int startIndex, int length);

Parameters

This method accepts the following parameters −

  • startIndex: It represents the starting position of a substring in this instance of string.
  • length: It represents the length of the substring in this instance of string.

Return Value

This method returns a Unicode character array whose length depends on the specified length. If length is not specified, it returns the Unicode charter array of the entire string.

Example 1: Convert a String to Character Array

Following is a basic example of the ToCharArray() method. Here, we use the default ToCharArray method to convert an entire string into a character array −

using System;
class Program {
   public static void Main() {
      string str = "Hello, tpians!";
      char[] ToCharArray = str.ToCharArray();
      foreach (char c in ToCharArray)
      {
          Console.Write(c + " ");
      }
   }
}

Output

Following is the output −

H e l l o ,   t p i a n s ! 

Example 2: Convert a Substring to Character Array

Let's look at another example. Here, we use the ToCharArray() method to convert substring of this string into a character array −

using System;
class Program {
   public static void Main() {
      string str = "Hello, tpians!";
      char[] ToCharArray = str.ToCharArray(3, 9);
      foreach (char c in ToCharArray)
      {
          Console.Write(c + " ");
      }
   }
}	

Output

Following is the output −

l o ,   t p i a n 

Example 3: Modifying a String Using ToCharArray

In this example, we convert the string into character arrays using the ToCharArray() method. We then Modified the character array −

using System;
class Program {
   static void Main() {
      string str = "Hello, tutorialspoint";
      
      char[] charArray = str.ToCharArray();

      // Modify the char array ( replace all 'o' with '0')
      for (int i = 0; i < charArray.Length; i++) {
         if (charArray[i] == 'o') {
            charArray[i] = '0';
         }
      }
      // Create a new string from the modified char array
      string modifiedString = new string(charArray);
      Console.WriteLine("Original String: " + str);
      Console.WriteLine("Modified String: " + modifiedString);
   }
}

Output

Following is the output −

Original String: Hello, tutorialspoint
Modified String: Hell0, tut0rialsp0int
csharp_strings.htm
Advertisements