Home »
C#.Net
String.ToCharArray() method with example in C#
C# String.ToCharArray() method: Here, we are going to learn about the ToCharArray() method of String class with example.
Submitted by IncludeHelp, on March 17, 2019
C# String.ToCharArray() Method
String.ToCharArray() method is used to get the character array of a string, it copies the characters of a this string to a Unicode character array.
Syntax:
char[] String.ToCharArray();
char[] String.ToCharArray(int start_index, int length);
Parameter:
- In first syntax there is no parameter, it returns character array of complete string.
- In second syntax, there are two parameters: start_index - from where you want to copies the string characters to the Unicode char[], and length – total number of characters to be copied.
Return value: In both of the cases, it returns char[].
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 !
Input:
string str = "Hello world!";
Function call:
//converting 5 characters from 6th index
char[] char_arr = str.ToCharArray(6, 5);
Output:
char_arr: 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!";
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();
//converting 5 characters from 6th index
char_arr = str.ToCharArray(6, 5);
//printing char[]
Console.WriteLine("char_arr...");
foreach (char item in char_arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
str: Hello world!
char_arr...
H e l l o w o r l d !
char_arr...
w o r l d
Reference: String.ToCharArray() Method