tags:

views:

283

answers:

8

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));
    }
A: 
        List<int> ints = new List<int>();

        foreach (char c in result.ToCharArray())
        {
            ints.Add(Convert.ToInt32(c));
        }
Asad Butt
I'm getting 48 for 0 and 49 for 1 (ASCII values). How to convert them to the correct integer?
NLV
It's probably overkill (due to the implicit conversion of `c` to type `string`), but you could use `Integer.Parse(c)`. I would refrain from simply subtracting 48 to get the digit value, since that will only work for ASCII/ANSI characters, not for other Unicode digit characters.
stakx
No need to call `ToCharArray()`, since type `string` is `IEnumerable<char>`. You can therefore abbreviate to `foreach (var c in result)`.
stakx
@stakx: Which other digits are you actually expecting to see? And are you sure that int.Parse will handle them? I don't think there's any indication here that a solution coping with Arabic digits etc is required.
Jon Skeet
+2  A: 
string result = "01234";
List<int> list = new List<int>();
foreach (var item in result)
{
    list.Add(item - '0');
}
Darin Dimitrov
+1  A: 

Index into the string to extract each character. Convert each character into a number. Code left as an exercise for the reader.

Bevan
Thank you. Actually i did that. But i'm getting them as ASCII values.
NLV
+3  A: 

You could use LINQ:

var ints = result.Select(c => Int32.Parse(c.ToString()));

Edit: Not using LINQ, your loop seems good enough. Just use Int32.Parse instead of Convert.ToInt32:

List<int> ints = new List<int>();

foreach (char c in result.ToCharArray())
{
    ints.Add(Int32.Parse(c.ToString()));
}
Jens
2.0 don't have linq
jdv
@jdv: The question didn't have 2.0 initially.
Guffa
Yes i added it later.
NLV
+3  A: 

Loop the characters and convert each to a number. You can put them in an array:

int[] digits = result.Select(c => c - '0').ToArray();

Or you can loop through them directly:

foreach (int digit in result.Select(c => c - '0')) {
   ...
}

Edit:
As you clarified that you are using framework 2.0, you can apply the same calculation in your loop:

List<int> ints = new List<int>(result.Length);

foreach (char c in result) {
    ints.Add(c - '0');
}

Note: Specify the capacity when you create the list, that elliminates the need for the list to resize itself. You don't need to use ToCharArray to loop the characters in the string.

Guffa
Cool, I've never seen '1'-'0'==1
machine elf
+3  A: 

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:

List<int> integers = new List<int>(text.Length);
foreach (char c in text)
{
    integers.Add(c - '0');
}

Not as neat, but it will work. Alternatively:

List<char> chars = new List<char>(text);
List<int> integers = chars.ConvertAll(delegate(char c) { return c - '0'; });

Or if you'd be happy with an array:

char[] chars = text.ToCharArray();
int[] integers = Arrays.ConvertAll<char, int>(chars, 
                            delegate(char c) { return c - '0'; });

Original answer

Some others have suggested using ToCharArray. You don't need to do that - string already implements IEnumerable<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':

IEnumerable<int> digits = text.Select(x => x - '0');

If you want this in a List<int> instead, just do:

List<int> digits = text.Select(x => x - '0').ToList();
Jon Skeet
Hi Jon. I added 2.0 in the title later after seeing lot of replies using lambda expressions and linq.
NLV
A: 
    static int[] ParseInts(string s) {
        int[] ret = new int[s.Length];
        for (int i = 0; i < s.Length; i++) {
            if (!int.TryParse(s[i].ToString(), out ret[i]))
                throw new InvalidCastException(String.Format("Cannot parse '{0}' as int (char {1} of {2}).", s[i], i, s.Length));
        }
        return ret;
    }
machine elf
+1  A: 

another solution...

string numbers = "012345";
List<int> list = new List<int>();

foreach (char c in numbers)
{
    list.Add(int.Parse(c.ToString()));
}

no real need to do a char array from the string since a string can be enumerated over just like an array.

also, the ToString() makes it a string so the int.Parse will give you the number instead of the ASCII value you get when converting a char.

Eclipsed4utoo