Click here to Skip to main content
15,905,971 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i m a new c# coder, i have problem in converting a string. Actually the string will be taken input from user. Lets put it directly here

C#
string input = "1+23+45+65+55+12";


I need to convert the above string to int, so that i get the result of it.

I tried
C#
Convert.ToInt32(input);
and
C#
int.Parse(input);
but not working, please help me out.
Posted

It won't - you need to evaluate it as an expression. Have a look at this: A Tiny Expression Evaluator[^] - it should help.
 
Share this answer
 
The methods you are using handle single numbers not expressions. For parsing expressions you need to build, precisely, a parser.
On the other hand, provided your expressions format is simple as the one in the example, you can build the parser very quickly, e.g.
C#
string expr = "1+23+45+65+55+12";

string[] num = expr.Split(new char[] { '+' });
int sum = 0;
foreach (var s in num)
{
  sum += int.Parse(s);
}
Console.WriteLine("sum =  {0}", sum);
 
Share this answer
 
v3
You can use below function:

C#
public static double Evaluate(string expression)
        {
            System.Data.DataTable table = new System.Data.DataTable();
            table.Columns.Add("expression", string.Empty.GetType(), expression);
            System.Data.DataRow row = table.NewRow();
            table.Rows.Add(row);
            return double.Parse((string)row["expression"]);
        }

Reference:
http://stackoverflow.com/questions/6052640/in-c-sharp-is-there-an-eval-function[^]

Thanks,
Jitendra

[edit]code block added[/edit]
 
Share this answer
 
v2
Comments
Sachin Dan 25-Nov-12 10:37am    
For metro style app System.Data namespace not available. What to do?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900