C # - How to convert keyboard string data to Char?

3

Good community!

I am new to the C # Language and I am doing a program where 3 phenotypes are created (ie 3 vectors, each size 4) where 2 are father and mother, of these 2 the child has to be generated (the 3rd vector) , the user will have to fill in the vectors manually with any letter of the alphabet (AZ or az, whether uppercase or lowercase) since these represent the genes and from these the child is generated (bearing in mind that the capital letter are the dominant genes ).

I'm going to the point, as far as my logic goes, I can say that I know how to do the program, the problem is how do I convert the keyboard data (since the input data from the keyboard is Strings type) to Char type? ?

In the program I have defined the vectors like this:

char[] Padre = new char[4];
char[] Madre = new char[4];
char[] Hijo = new char[4];

    void pMH()
    {
        char gen;
        char aux, aux1;
        Console.WriteLine ("Genes del Padre");
        for (int i = 0; i < Padre.Length; i++) 
        {
            Console.Write ("Ingrese gen [" + (i + 1) + "]: ");
            gen = Console.ReadLine();
            Padre [i] = gen;
        }

As you can see I have a char gen; where there is stored the data entered the keyboard, but I throw error, obviously the error is that you can not save a String in a Char, I have tried to convert it necessarily something like this: gen = (char)Console.ReadLine(); and I can not do it.

Please, I have searched for google and I get results using the method .ToCharArray(); but I do not understand how it works, try to implement it in my program but I can not understand that method and obviously it does not work.

I hope you can help me with that problem, please.

Thank you very much for your attention, have a Happy Week:)

    
asked by Neither Castañeda 28.04.2017 в 03:41
source

2 answers

2

The ToCharArray() method converts the String to Array of Chars , that method could be used and in turn access the posición 0 of the Array that will be the first key pressed.

gen = Console.ReadLine().ToCharArray()[0];
Padre[i] = gen;

The other option would be using the method Console.ReadKey () , with an additional line break, so that the console keys are not shown pasted.

 for (int i = 0; i < Padre.Length; i++)
 {
   Console.Write("Ingrese gen [" + (i + 1) + "]: ");
   gen = Console.ReadKey().KeyChar; /* Obtener el Caracter */
   Console.WriteLine(); /* Salto de Línea adicional */
   Padre[i] = gen;
 }
    
answered by 28.04.2017 / 03:54
source
2

Strictly speaking, it is not possible to convert a string to a character, because strings can have several characters.

But if you just want to get the first character of the string, this can be done using a syntax as if the string were an array. No need to use .ToCharArray() , which creates an unnecessary additional array:

gen = Console.ReadLine()[0];
    
answered by 28.04.2017 в 05:43