Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a string like str = " 4+ 6 * 30";. I have to perform an arithmetic operation on this using C#; My solution to this problem is as follows.

     string temp = " 4 + 6 * 5";
     int firstNaum = 0;
     int secondNum = 0;
     int ThirdNum = 0;
     int finalResults = 0;
    //Spliting strings
    string[] withoutOperator = temp.Split('\t',' ','*' , '+');
    //Iterating strings 
    int counter = 0;
    foreach (var res in withoutOperator)
    {
        if (!string.IsNullOrEmpty(res) && counter ==1)
        {
            firstNaum = Convert.ToInt32(res);
        }
        if (!string.IsNullOrEmpty(res) && counter== 4)
        {
            secondNum = Convert.ToInt32(res);
        }
        if (!string.IsNullOrEmpty(res) && counter == 7)
        {
            ThirdNum = Convert.ToInt32(res);
        }
        counter += 1;
    }
    finalResults = firstNaum + secondNum * ThirdNum;
share|improve this question
3  
The process that you're using is very tightly coupled to your example, and not at all extensible to other input strings. – krillgar Jul 24 '14 at 16:17

3 Answers 3

Your solution is very limited. As it only take a string in in the following format x1 x2 x3, and apply to the function x1+x2*x3.

To build an expressional calculator, you need to go through these steps :

  1. Segmentate the expression into a list of tokens
  2. Parse the tokens into recognizable lexemes(numbers, operator, parenthesis, etc)
  3. Transform the list into a tree structure based on the order of operations
  4. Calculate the result of top root, which requires the results from its branch(es)
share|improve this answer
1  
However, such expressions are extremely easy to parse and calculate, as the Shunting-Yard algorithm can be used to evaluate the tokens. So of your four steps, only two remain: tokenization (I don't get why you split that into two phases), and evaluation via Shunting-Yard. – amon Jul 24 '14 at 16:41

Can you clarify what you want us to feed back on.

My thoughts are:

  1. Use a library that already performs infix mathematical parsing because the process is relatively complex but has been "solved" many times before.
  2. Your code assumes a very strict order in the the operations. That doesn't make it very extensible.
  3. Try adding validation. instead of Convert.ToInt32(res), use int.TryParse(res, out n). if the function returns false, you know the parse failed and you can handle it as you feel fit.
  4. Maybe Trim() your res on each loop - although you will need to assign it to a new variable (e.g. var res2 = res.Trim();)
share|improve this answer

One of the simplest and easiest ways to evaluate math expressions is to use the Compute method of the DataTable class:

DataTable dt = new DataTable();
int answer = (int)dt.Compute("2+(4*3)*4", "");

answer is 50.

One caveat you'll have to trap exceptions to catch invalid expressions.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.