C#字符串转换为具有复杂结构的int [英] C# string to int with complex structure

查看:94
本文介绍了C#字符串转换为具有复杂结构的int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是一个新的C#编码器,在转换字符串时遇到问题.实际上,该字符串将取自用户的输入.让我们直接放在这里

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";



我需要将上面的字符串转换为int,以便得到它的结果.

我尝试了



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

I tried

Convert.ToInt32(input);

int.Parse(input);

但不能正常工作,请帮帮我.

but not working, please help me out.

推荐答案

它不会-您需要将其评估为表达式.看看以下内容:微小的表达评估器 [
It won''t - you need to evaluate it as an expression. Have a look at this: A Tiny Expression Evaluator[^] - it should help.


您正在使用的方法处理单个数字而不是表达式.为了解析表达式,您需要精确地构建 parser .
另一方面,假设您的表达式格式像示例中一样简单,则可以非常快速地构建解析器,例如
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);


您可以使用以下功能:

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"]);
        }


参考:
> http://stackoverflow.com/questions/6052640/in-c- Sharp-is-there-an-eval-function [ ^ ]

谢谢,
Jitendra

[edit]添加了代码块[/edit]


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

Thanks,
Jitendra

[edit]code block added[/edit]


这篇关于C#字符串转换为具有复杂结构的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆