Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string numbers to Array C#

Tags:

c#

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?

like image 272
Ye Myat Aung Avatar asked Apr 07 '26 17:04

Ye Myat Aung


2 Answers

    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();
like image 77
jgauffin Avatar answered Apr 09 '26 07:04

jgauffin


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

like image 41
crypted Avatar answered Apr 09 '26 05:04

crypted



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!