Click here to Skip to main content
12,956,512 members (67,980 online)
Rate this:
Please Sign up or sign in to vote.
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

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
but not working, please help me out.
Posted 24-Nov-12 3:25am
Rate this: bad
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.
Rate this: bad
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);
Rate this: bad
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();
            return double.Parse((string)row["expression"]);



[edit]code block added[/edit]
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)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,869
CHill60 3,550
Maciej Los 3,302
ppolymorphe 2,080
Jochen Arndt 1,973

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 24 Nov 2012
Copyright © CodeProject, 1999-2017
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