Home » C#.Net

Convert string to character array in C#

C# converting string to char[]: Here, we are going to learn how to convert a string to character array in C#?
Submitted by IncludeHelp, on March 17, 2019

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

Converting string to char[]

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:

    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 convert string to characters array using String.ToCharArray() method

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


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.