Home > Mobile >  How do I add integers to char[] array?
How do I add integers to char[] array?

Time:03-03

So I have to write a code that picks our random numbers from 1 to 100 and add them to a char[] array. But I'm having some difficulty doing so as I can only add the numbers to the array if I convert them to a char using (char) which changes the number. Can someone please help me? Thanks,

 public char[] CreationListe(int nmbrevaleurTirés)
    {
        char[] l = new char[nmbrevaleurTirés];
        for (int i = 0; i < nmbrevaleurTirés; i  )
        {
            l[i] = (char)(new Random().Next(1, 101));

        }
        return l;
    }

CodePudding user response:

use ToChar() method of Convert class.

Convert.ToChar(new Random().Next(1, 101))

CodePudding user response:

You cannot convert an integer larger then 9 into a char because it's considered as 2 chars, i.e. 10 will be considered as 1 and 0.

so I would recommend adding it to an array of strings

CodePudding user response:

Personally, I'd use an int[] array instead

There shouldn't be any problem in storing ints up to 65535 in a char but you will have to cast it back to an int if you don't want it to be weird:

public static void Main()
{
   var x = CreationListe(200);
   foreach(var c in x)
     Console.WriteLine((int)c);  //need to cast to int!
    
}

public static char[] CreationListe(int nmbrevaleurTirés)
{
    char[] l = new char[nmbrevaleurTirés];
    for (int i = 0; i < nmbrevaleurTirés; i  )
    {
        l[i] = (char)(new Random().Next(1, 65536));

    }
    return l;
}

https://dotnetfiddle.net/z5yoBn

If you don't cast it back to int, then you'll get the char at that character index in the unicode table. If you've put 65 into a char, you'll get A when you print it, for example. This is because A is at position 65 in the table:

ascii table

(ASCII table image posted for brevity's sake)

  •  Tags:  
  • c#
  • Related