Convert String to Character Array in C#


In C# programming, you'll often find yourself needing to perform operations on individual characters within a string. In such scenarios, converting a string into a character array can be highly useful. This article will provide an in-depth guide on how to convert a string to a character array in C#, a fundamental skill in many programming tasks.

Understanding Strings and Character Arrays in C#

In C#, a string is a sequence of characters, while a character array (char[]) is an array that stores individual characters as its elements. For example, consider the following string and character array −

string word = "Hello";
char[] letters = { 'H', 'e', 'l', 'l', 'o' };

In this example, word is a string that stores "Hello", and letters is a character array that stores 'H', 'e', 'l', 'l', and 'o'.

Converting a String to a Character Array

Converting a string to a character array in C# is straightforward. The String class provides a method called ToCharArray(), which returns a new character array from the current string.

Example

Here's an example −

using System;

class Program {
   static void Main() {
      string word = "Hello";
      char[] letters = word.ToCharArray();

      foreach (char letter in letters) {
         Console.WriteLine(letter);
      }
   }
}

In this example, we first define a string word with the value "Hello". We then call the ToCharArray() method on word to convert it to a character array. The result is assigned to letters. We then print each character in letters to the console.

Output

H
e
l
l
o

Working with the Character Array

Once you have converted the string to a character array, you can manipulate the characters in various ways. For example, you can reverse the array, sort it, or even change individual characters. This flexibility is one of the reasons why converting a string to a character array can be so useful.

Example

Here's an example of reversing the character array −

using System;

class Program {
   static void Main() {
      string word = "Hello";
      char[] letters = word.ToCharArray();

      Array.Reverse(letters);

      foreach (char letter in letters) {
         Console.WriteLine(letter);
      }
   }
}

In this example, after converting the string to a character array, we use the Array.Reverse method to reverse the order of the characters.

Output

ol
l
e
H

Conclusion

In C#, converting a string to a character array is a simple process made possible by the ToCharArray() method of the String class. Understanding this conversion allows you to manipulate individual characters within a string, opening up a wide array of possibilities for string and character operations in your C# programming tasks.

Updated on: 24-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements