;

How To Convert String to Char Array in C#


Tutorialsrack 18/05/2020 C#

In this article, we will learn how to convert string to char array in C#. For Converting a string to a character array, we used the String.ToCharArray() method of the String class. 

The ToCharArray() method has the following two overloaded forms:

  1. String.ToCharArray() - This method copies characters of the string to a Unicode character array.
  2. String.ToCharArray(Int32, Int32) - This method copies characters of the substring to a Unicode character array.

Convert String to Char[] in C#

Convert String to Char[] in C#
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How To Convert String To Char Array in C# */
        static void Main(string[] args)
        {
            string str = "Tutorialsrack.com";
            Console.WriteLine("Original String: {0}\n",str);
            // Convert String to Char Array
            char[] ch = str.ToCharArray();

            Console.WriteLine("Print the String After Converted into Char Array");

            // Print The Character
            foreach(var c in ch)
            {
                Console.WriteLine(c);
            }
            //Hit ENTER to exit the program
            Console.ReadKey();
        }
    }
}
Output
Original String: Tutorialsrack.com
 
Print the String After Converted into Char Array
T
u
t
o
r
i
a
l
s
r
a
c
k
.
c
o
m

If you have a single character string, You can also try this:

string str = "A";
char character = char.Parse(str);

//OR 

string str = "A";
char character = str.ToCharArray()[0];
 
I hope this article will help you to understand how to convert string to char array in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags