.ToCharArray()
Published Dec 14, 2024
Contribute to Docs
The .ToCharArray()
method in C# converts a string into an array of characters, where each character in the string becomes an element in the resulting array. This allows for the manipulation or iteration of individual characters.
Syntax
char[] arrayName = stringName.ToCharArray();
stringName
: The string to be converted into a character array.arrayName
: The resulting array containing individual characters from the string.
Optional Parameters
The .ToCharArray()
method can also take optional parameters to convert a specific substring into a character array:
char[] substringArray = stringName.ToCharArray(startIndex, length);
startIndex
: The zero-based index where the substring starts.length
: The number of characters to include in the resulting array, starting fromstartIndex
.
Examples
Split into Individual Characters
Here’s an example of using .ToCharArray()
to split a string into individual characters:
using System;class Program{static void Main(){string greeting = "Hello, World!";char[] charArray = greeting.ToCharArray();foreach (char c in charArray){Console.WriteLine(c);}}}
The output of the above code will be as follows:
Hello,World!
Converting a Substring to a Character Array
using System;class Program{static void Main(){string phrase = "Convert this string!";char[] partialArray = phrase.ToCharArray(8, 4);foreach (char c in partialArray){Console.WriteLine(c);}}}
The output of the above code will be as follows:
this
Codebyte Example
Run the following codebyte example to see how .ToCharArray()
works in C#:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours