Monday, July 14, 2014

Convert string to a char array in C#

It's not complicated. You just have to know how to do it.

   public class ArrayChange
   {
       static char[] charArray;//declare before Main method
       public static void Main(string[] args)
      {
         Console.WriteLine("Enter your name: ");
         string input = Console.ReadLine();
         charArray = input.ToCharArray();
      }//end Main method
   }//end class

This first line, of course, prompts the user to enter a string. The second line stores that input in a string variable called "input". The third line converts input to a char array and stores it in the array called "charArray".

If you try to store the user input directly into a char array, you'll get a red squiggly line telling you that you cannot implicitly convert a string, which is the user input, into a char array. In other words, you can't just say that apples = oranges.

So your next thought is probably to do this:

Convert.ToCharArray(Console.ReadLine());

Good idea. Makes sense to me, but Convert class does not contain a ToCharArray method, just ToChar. So when you want apples = oranges, you need a middleman. In our case, that middleman is string input, which stores the user input as a string. Since strings are made of characters, we can just dump those characters into a char array as we did in the third line.




No comments:

Post a Comment