简体   繁体   中英

How do I can assign element of string value to int value?

I'm trying to write a program, that will sum numbers of a string value(for example I have string value "123" and I'd like sum these numbers to get int value "5").
Additional information : I need to do it by recursion .
How do I can do that?
I tried this code:

static void SumString(string num, ref int index, ref int result) 
{
    if(index >= num.Length - 1)
    {
        Console.WriteLine(result);
        return;
    }    
            
        
    char[] arr = new char[num.Length];

    arr[index] = num[index];

    result += Convert.ToInt32(arr[index]);

        

    index++;

    SumString(num, ref index, ref result);
}

You can use DataTable.Compute

using System.Data;

DataTable dt = new DataTable();
var v = dt.Compute(num,""); 

Your code has a couple of problems.

Convert.ToInt32(num[index] will give you value 49 which is asci value of 1.

Then you are not ignoring the + character as well. so you need to skip it.

The correct solution would be

static void SumString(string num, ref int index, ref int result)
{
    if (index >= num.Length)
    {
        Console.WriteLine(result);
        return;
    }

    if (index % 2 == 0)
        result += (Convert.ToInt32(num[index]) - '0');

    index++;

    SumString(num, ref index, ref result);
}

you can use an expression evaluator also if looking for some external library.

https://github.com/codingseb/ExpressionEvaluator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM