Home > front end >  How do I can assign element of string value to int value?
How do I can assign element of string value to int value?

Time:10-23

I'm trying to write a program, that will sum numbers of a string value(ex. "1 2 3" = 1 2 3). When i'm tried to get first element of string value("3"), convert and add it to Result, IDE straightaway gave him - 51. Can anyone explain me, why does it happen so?

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

        

    index  ;

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

CodePudding user response:

You can use DataTable.Compute

using System.Data;

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

CodePudding user response:

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

  • Related