2

Lets say I have a string str = "012345"; I want to convert it to an array which would look like intAry = {0, 1, 2, 3, 4, 5};. Any ideas?

I tried like this..

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

But what went to array are like 48, 49, etc. Which correct method should I use here?

1
  • Just minus the ASCII code of '0', which is 48 (in decimal). In ASCII and Unicode, digits are consecutive in sequence. This is a pretty standard trick when using "old" programming languages (e.g. C). Commented Apr 20, 2011 at 11:30

3 Answers 3

12
    for (int i = 0; i < str.Length; i++)
        intAry[i] = str[i] - '0';

Update

Or as LINQ:

var array = str.Select(ch => ch - '0').ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

I think you mean str[i] - '0'
Should that not be str[i] - '0'?
you menat intAry[i] = Convert.ToInt32(str[i] - '0');
Yup. str[i] - '0' gave me what I wanted :)
4

How about this.

  string source = "12345";
   Int32[] array=source.Select(x => Int32.Parse(x.ToString())).ToArray();

but remember every character within source should be convertible to an Integer

Comments

0

48, 49, etc. went in because that is the ASCII value of '0'. If you subtract '0' from the char, it will give you the correct integer. No convert required.

intAry[i] = str[i] - '0';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.