0

This question is different as it tackles the issue of converting a char to an int when adding to an integer array.

The following piece of code, I am trying to implement a string of integers into a int[] array in C#.

My desired output is an array of:

12345678910

This is my code, however, the output of this is not what I desire:

string numbers = "12345678910";

int[] array = new int[numbers.Length];

for (int i = 1; i <= numbers.Length; i++)
{
    array[i - 1] = numbers[i-1];
}

foreach(var y in array)
{
    Console.Write(y);
}

Output of given code:

4950515253545556574948

Can somebode tell me why I am getting this output, and what I can do to fix this? Thank you!

Edit: Changed my code and it works using this:

for (int i = 0; i < numbers.Length; i++)
{
     array[i] = int.Parse(numbers[i].ToString());
}
13
  • 3
    You are converting each character to its code and then displaying the code, not the associated digit Commented Jan 16, 2019 at 16:03
  • 4
    Strings are arrays of char objects. What you see are the numeric values of individual characters. Commented Jan 16, 2019 at 16:03
  • 1
    Digits come one after another and Char objects can be converted to int implicitly. You could use numbers.Select(c=>(int)c-'0').ToArray() to get an array of numbers from the string. Commented Jan 16, 2019 at 16:05
  • 1
    Quick side note: Your for loop is unnecessarily redundant. for (int i = 1; i <= numbers.Length; i++) array[i - 1] = numbers[i-1]; can be written a lot easier such as for (int i = 0; i < numbers.Length; i++) array[i] = numbers[i]; -- Using this approach, you don't have to remember to put i-1 in every index accessor. Commented Jan 16, 2019 at 16:05
  • 1
    Also if you code your for loop as for (int i = 0; i < numbers.Length; i++ you don't have to do the whole i - 1 to get the right index Commented Jan 16, 2019 at 16:05

1 Answer 1

2

First of all, I don't think you'll be able to distinguish a two digit number using this method.

I refer to this part of your code: string numbers = "12345678910"; Iterate through your string characters and parse to Int (if that's what's required) (credit) (credit)

 foreach (char character in yourString)
        {
            int x = (int)Char.GetNumericValue(character);                
            //code to add to your array of ints
        }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.