Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# -> 7 in a string, convert to int returns 55?

Evening… revising some C# coding questions///

10 Random numbers
7319018271
….so I put brackets around the numbers and made it a string…
created an array with [10]…idea is to iterate through the string and convert each string var to an int and add to myArray…problem being…why does 7 return as 55?

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

   var Numbers = "7319018271";

        int[] myArray = new int[10];

        for(int i = 0; i < Numbers.Length; i++)
        {
            myArray[i] = Numbers[Convert.ToInt32(i)];
        }

        int test = myArray[0];

>Solution :

To explain 55, that’s the ASCII code for the character 7.

The problem you have your code here is that you have Convert.ToInt32 in the wrong place. Currently you’re converting i (an int) to an int. The other issue is that passing a char to Convert.ToInt32 will still result in 55, so you need to first convert it to a string. Fixing both of these problems, we end up with the following:

myArray[i] = Convert.ToInt32(Numbers[i].ToString());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading