interpret string C#

Asked

Viewed 105 times

4

hello, needed to resolve a string with an account (e.g. 2 + 2) in C# and return an integer (e.g. 4)

static void Main(string[] args)
{
    string str = "2 + 2";
    int resultado = Calcular(str);
    Console.WriteLine("Resultado => {0}",resultado);
    Console.ReadLine();
}

any hint?

2 answers

3


The library Ncalc simplifies this for you. Install it by Nuget:

Install-Package ncalc

Then use it that way:

using NCalc;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "2 + 2";
            var expressao = new Expression(str);
            Console.WriteLine("Resultado => {0}", expressao.Evaluate());
            Console.ReadLine();
        }
    }
}
  • Okay, I tested it here and it worked, just one more thing, if I have something like "solve the average of these values: 2.4", is there any way I can average it, or at least remove the text and just leave the values with the comma?

  • @Jacksonjoségomesdovalle a generic method that does this would be complicated, you need to have a rule to know how to extract the numbers from the text. One way would be to take out anything other than a number and a comma, but then if you typed a comma into her sentence, it wouldn’t work anymore. Then maybe you had to find the first occurrence of some number (ex: 2) and take everything you have from there until the last occurrence of some number (in this case it would take 2.4). Then you do var nums = textoExtraido.Split(','); and then something like var media = nums.Select(n => Convert.ToInt32(n)).Average();.

  • OK, I’ll try thanks for the answer

1

I use the following function:

        /// <summary>
    /// Calcular Formulas
    /// </summary>
    /// <param name="evaluationString"></param>
    /// <returns></returns>
    public static string CalculateFormula(string evaluationString)
    {
        Microsoft.JScript.Vsa.VsaEngine en = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
        Object result = Microsoft.JScript.Eval.JScriptEvaluate(evaluationString, en);

        return result.ToString();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.