Reader Level:
Articles

Convert string to char array in C#

By Mahesh Chand on July 04, 2012
How to convert a string to a char array using C#.
  • 0
  • 0
  • 52033

Download Free book: Programming Strings in C#

The ToCharArray method of the string class converts a string to a character array. The following code snippet creates a string into a char array.

string sentence = "Mahesh Chand";
char[] charArr = sentence.ToCharArray();
foreach (char ch in charArr)
{
    Console.WriteLine(ch);
} 

Here is a complete sample code:

public void StringToCharArray()
{

    // Convert string to char array
    string sentence = "Mahesh Chand";
    char[] charArr = sentence.ToCharArray();
    foreach (char ch in charArr)
    {

        Console.WriteLine(ch);
    } 

    // Convert char array to string
    char[] chars = new char[10];
    chars[0] = 'M';
    chars[1] = 'a';
    chars[2] = 'h';
    chars[3] = 'e';
    chars[4] = 's';
    chars[5] = 'h';
    string charsStr = new string(chars);
    string charsStr2 = new string(new char[]
    {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'});
    Console.WriteLine("Chars to string: {0}", charsStr);
    Console.WriteLine("Chars to string: {0}", charsStr2);
} 

The output looks like the following:

Str2BtArr.png


Download Free book: Programming Strings in C#




Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  Mahesh has been awar... Read more

COMMENT USING

Trending up