Convert string numbers to Array C#

前端 未结 3 1508
深忆病人
深忆病人 2020-12-11 11:28

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?

相关标签:
3条回答
  • 2020-12-11 11:39
        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();
    
    0 讨论(0)
  • 2020-12-11 11:43

    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

    0 讨论(0)
  • 2020-12-11 11:47

    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';
    
    0 讨论(0)
提交回复
热议问题