TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# ToCharArray: Convert String to Array

Call the ToCharArray method to convert a string to a char array.
ToCharArray. This method converts strings to character arrays. It is called on a string and returns a new char array. The original string is left unchanged.
We can manipulate this array in-place, which we cannot do with a string. This makes many performance optimizations (some significant) possible.Char ArrayChar
An example. First we use ToCharArray() to get a character array from the contents of a string. The example uses an input string, and then assigns a char array to the result of ToCharArray.Strings

Next: It uses a for-loop to get each character in the array, finally writing it to the Console.

ForConsole
C# program that uses ToCharArray using System; class Program { static void Main() { // Input string. string value = "The Dev Codes"; // Use ToCharArray to convert string to array. char[] array = value.ToCharArray(); // Loop through array. for (int i = 0; i < array.Length; i++) { // Get character from array. char letter = array[i]; // Display each letter. Console.Write("Letter: "); Console.WriteLine(letter); } } } Output Letter: D Letter: o Letter: t Letter: Letter: N Letter: e Letter: t Letter: Letter: P Letter: e Letter: r Letter: l Letter: s
Benchmark, ToCharArray. Here we measure the performance of ToCharArray. We copy a string to a char array with 2 versions of C# code.

Version 1: This uses ToCharArray. We make sure the resulting string has a correct first character each time.

Version 2: We allocate a char array of the required length, and then copy each character in from the source string.

Result: ToCharArray is faster on a 300-char string. But if we try a smaller string, ToCharArray may be slower—make sure to test.

C# program that times ToCharArray using System; using System.Diagnostics; class Program { const int _max = 2000000; static void Main() { // Create 500-char string. string text = new string('P', 500); // Version 1: use ToCharArray. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { char[] result = text.ToCharArray(); if (result[0] != 'P') { return; } } s1.Stop(); // Version 2: copy chars from string with loop. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { char[] result = new char[text.Length]; for (int v = 0; v < text.Length; v++) { result[v] = text[v]; } if (result[0] != 'P') { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 221.32 ns ToCharArray 274.00 ns new char[], for loop
Uses. With ToCharArray, the char array you receive is mutable. You can change characters. The method is ideal for transforming chars (like in ROT13, or uppercasing the first letter).Uppercase First LetterReverse StringROT13

Also: Often you will need to change your char array back to a string. You can use the new string constructor for this.

String ConstructorConvert Char Array, String
Internals. ToCharArray uses unsafe code that manipulates pointers, along with the private wstrcpyPtrAligned method in the base class library.

And: Optimized C++ code is normally faster than doing the same thing in managed code, which has to check array bounds.

Note: ToCharArray makes a complete pass over the string, so if you do not require that, filling character arrays manually may be faster.

A summary. ToCharArray is often useful. It returns a character array filled with the string's characters. We can modify this array in-place. This improves the performance of code.
Review, performance. We looked at practical uses of ToCharArray and its internals in the base class library. It has advanced optimizations.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf