Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 4:25am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

It won't - you need to evaluate it as an expression. Have a look at this: A Tiny Expression Evaluator[^] - it should help.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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  
v2
Comments
Sachin Dan at 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)

  Print Answers RSS
0 OriginalGriff 325
1 DamithSL 300
2 Sergey Alexandrovich Kryukov 289
3 CPallini 235
4 Maciej Los 215
0 OriginalGriff 5,455
1 DamithSL 4,422
2 Maciej Los 3,860
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,010


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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100