Convert string to character array in C#

C# changing over the string to char[]: Here, we will figure out how to change over a string to character cluster in C#?

Given a string and we need to change over it into character exhibit in C#.

Changing over the string to char[]

To change over a given string in char[] (character exhibit), we use String.ToCharArray() technique for String class, it is called with this string and

returns a characters cluster, it changes over characters of the string to a variety of Unicode characters.

Example:

    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# Example to change over the string to characters cluster utilizing String.ToCharArray() strategy:

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[]

Leave a Comment

error: Alert: Content is protected!!