Converting a line number to a sequence of digits -.Net 2.0

For string

string result = "01234"

I want to get single integers 0,1,2,3,4 from a string.

How to do it?

1

The following code gives me ascii values

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

    foreach (char c in result.ToCharArray())
    {
        ints.Add(Convert.ToInt32(c));
    }
+3
source share
8 answers

EDIT: I did not notice the requirements of ".NET 2.0". If you are going to do a lot of this, you should probably use LINQBridge and see a later bit - especially if you can use C # 3.0 while it is still targeting 2.0. Otherwise:

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

Not so neat, but it will work. As an alternative:

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

Or, if you are happy with the array:

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

Original answer

ToCharArray. - IEnumerable<char>, . ; - Unicode "0":

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

List<int>, :

List<int> digits = text.Select(x => x - '0').ToList();
+4

LINQ:

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

Edit: LINQ, . Int32.Parse Convert.ToInt32:

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

foreach (char c in result.ToCharArray())
{
    ints.Add(Int32.Parse(c.ToString()));
}
+3

. :

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

:

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

Edit:
, 2.0, :

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

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

. , , . ToCharArray .

+3
string result = "01234";
List<int> list = new List<int>();
foreach (var item in result)
{
    list.Add(item - '0');
}
+2

. . .

+1

...

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

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

char , .

, ToString() , int.Parse ASCII, char.

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

        foreach (char c in result.ToCharArray())
        {
            ints.Add(Convert.ToInt32(c));
        }
0
    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;
    }
0

Source: https://habr.com/ru/post/1736769/


All Articles