Click here to Skip to main content
Sign Up to vote bad
good
See more: C#4.0
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
 
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
Convert.ToInt32(input);
and
int.Parse(input);
but not working, please help me out.
Posted 24 Nov '12 - 3:25


3 solutions

It won't - you need to evaluate it as an expression. Have a look at this: A Tiny Expression Evaluator[^] - it should help.
  Permalink  
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.
  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);
  Permalink  
You can use below function:
 
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]
  Permalink  
Comments
Sachin Dan - 25 Nov '12 - 10:37
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)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 OriginalGriff 345
1 Sergey Alexandrovich Kryukov 338
2 Arun Vasu 315
3 Maciej Los 208
4 Aarti Meswania 180
0 Sergey Alexandrovich Kryukov 9,755
1 OriginalGriff 7,549
2 CPallini 4,018
3 Rohan Leuva 3,362
4 Maciej Los 2,951


Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 24 Nov 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid