Convert string to character array in C#

C# converting string to char[]: In this tutorial, we will learn how to convert the given string to character array in C#? By IncludeHelp Last updated : April 09, 2023

Given a string and we have to convert it into character array in C#.

How to convert string to character array in C#?

To convert a given string in char[] (character array), we use String.ToCharArray() method of String class, it is called with this string and returns a characters array, it converts characters of the string to an array of Unicode characters.

Example to convert string to character array

string str = "Hello world!";
Function call:
char[] char_arr = str.ToCharArray();

char_arr: H e l l o   w o r l d !

C# program to convert string to character array

using System;
using System.Text;

namespace Test {
  class Program {
    static void Main(string[] args) {
      //string variable
      string str = "Hello world!";

      //converting string to char[]
      char[] char_arr = str.ToCharArray();

      Console.WriteLine("str: " + str);

      //printing char[]
      foreach(char item in char_arr) {
        Console.Write(item + " ");

      //printing types of string & char[]
      Console.WriteLine("Type of str: " + str.GetType());
      Console.WriteLine("Type of char_arr: " + char_arr.GetType());

      //hit ENTER to exit


str: Hello world!
H e l l o   w o r l d !
Type of str: System.String
Type of char_arr: System.Char[]

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.