Home > front end >  How do I convert the contents of a char array to their corresponding integer values in C#?
How do I convert the contents of a char array to their corresponding integer values in C#?

Time:11-17

I'm taking a string provided by the user and converting it to a char array by doing the following.

string userInput = Console.ReadLine();
char[] charArray = userInput.ToCharArray();

From there I want to loop through the entire char array and convert each index to its corresponding integer value, but this is where I'm having trouble.

If my string is "Hello World", My char array should look like this

{'H', 'e', 'l', 'l', 'o', '', 'W', 'o', 'r', 'l', 'd'}

Then the int array would look like this

{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}

This is the loop I've written to go through the char array:

for (int count = 0; count<charArray.Length; count  )
        {
            myInt = charArray[count]; 
        }

Using this loop, I know that the value of myInt continues to be changed until the loop terminates. Meaning the value of myInt will correspond the the int value of the last index of charArray. I've also tried using charArray[count] =..., but I can't figure out how to use this properly. Any insight would be greatly appreciated.

CodePudding user response:

You have it almost complete, but you can consider the following:

  • Where will the result will be stored?

If you have an array of X number of CHARS, then you will have to make an INT array of the same length.

int[] intArray=new int[charArray.Length];

Then you can assign each element to the corresponding "box"

for (int count = 0; count<charArray.Length; count  )
{
    intArray[count]= (int)charArray[count]; 
}

You might want to cast the char to int (the parentesis with the type in it is called cast, where you can convert one type of variable to another, whenever is possible)

CodePudding user response:

To get the int of the char you could do myInt = (int)(charArray[count] - ‘0’);

  •  Tags:  
  • c#
  • Related