Given a string
string result = "01234"
I want to get the separate integers 0,1,2,3,4 from the string.
How to do that?
1
The following code is giving me the ascii values
List<int> ints = new List<int>();
foreach (char c in result.ToCharArray())
{
ints.Add(Convert.ToInt32(c));
}
EDIT: I hadn’t spotted the “.NET 2.0” requirement. If you’re going to do a lot of this sort of thing, it would probably be worth using LINQBridge, and see the later bit – particularly if you can use C# 3.0 while still targeting 2.0. Otherwise:
Not as neat, but it will work. Alternatively:
Or if you’d be happy with an array:
Original answer
Some others have suggested using
ToCharArray. You don’t need to do that – string already implementsIEnumerable<char>, so you can already treat it as a sequence of characters. You then just need to turn each character digit into the integer representation; the easiest way of doing that is to subtract the Unicode value for character ‘0’:If you want this in a
List<int>instead, just do: