C# String - ToCharArray() Method
The C# ToCharArray() method returns an array of characters which contains the characters of a string or a part of string.
Note: This method can be overloaded by passing different type of arguments to it.
Syntax
public char[] ToCharArray(); public char[] ToCharArray(int startIndex, int length);
Parameters
startIndex |
Specify the start index of the substring in the given string. |
length |
Specify the length of the substring. |
Return Value
Returns the array of characters.
Exception
Throws ArgumentOutOfRangeException, if the startIndex or length is less than zero.
Example:
In the example below, ToCharArray() method is used to create an array of characters from the string called MyStr.
using System; class MyProgram { static void Main(string[] args) { string MyStr = "Hello World"; char[] arr1, arr2; arr1 = MyStr.ToCharArray(); arr2 = MyStr.ToCharArray(6, 5); Console.Write("arr1 contains: "); foreach (char c in arr1) Console.Write(c + " "); Console.Write("\narr2 contains: "); foreach (char c in arr2) Console.Write(c + " "); } }
The output of the above code will be:
arr1 contains: H e l l o W o r l d arr2 contains: W o r l d
❮ C# String Methods