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

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

Output:
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[]
      Console.WriteLine("char_arr...");
      foreach(char item in char_arr) {
        Console.Write(item + " ");
      }
      Console.WriteLine();

      //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
      Console.ReadLine();
    }
  }
}

Output

str: Hello world!
char_arr...
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 www.includehelp.com. All rights reserved.