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 Stringclass.
The ToCharArray() method has the following two overloaded forms:
String.ToCharArray() - This method copies characters of the string to a Unicode character array.
String.ToCharArray(Int32, Int32) - This method copies characters of the substring to a Unicode character array.
Note:
String.ToCharArray(int startIndex, int length) method can give the exception ArgumentOutOfRangeException if startIndex or length is less than zero or(startIndex + length) is greater than the length of current string instance.
If the specified length is 0 then it returns an empty array and will have zero length. If current or this instance is null or an empty string(“”) then it returns an empty array and will have zero-length
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!
Comments