How to convert a string into character array in C#?

Given a string. Learn, how can we convert it into a character array in C#?
[Last updated : March 19, 2023]

As we have discussed in character array in C# that strings are characters arrays are different in C#.Net, so it is required to convert string to character array, if we need to traverse of access character by character, that can be easily manageable using character array.

String to Character Array Conversion

To convert a string into a character array, we use string.ToCharArray() method which is a built in method provided by the .Net Framework, it is used to convert string to the character array.

C# program for string to character array conversion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {

      //string
      string str = "Hello, How are you?";

      int i = 0;

      //character array declaration
      char[] CH;

      //converting string to character array
      CH = str.ToCharArray();

      //printing character array character by character
      for (i = 0; i < CH.Length; i++) {
        Console.Write(CH[i] + "");
      }

      Console.WriteLine();
    }
  }
}

Output

Hello, How are you?

Explanation

In this program str is a string type variable, Using string.ToCharArray() method we copied the character of string str to CH.

And then, we are getting the length of the character array (CH) using Length property and printing character by character of CH (character array)

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.