提取字符串数学表达式变量 [英] Extract variables from string math expression

查看:473
本文介绍了提取字符串数学表达式变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要提取使用C#从数学表达式的变量。我写了这个代码和它的作品的权利:

I want to extract variables from math expression using c#. I wrote this code and it works right:

List<string> Variables = new List<string>();
string temp = string.Empty;
Console.WriteLine("Please enter ur expression");
string Expression = Console.ReadLine().Trim();
int Index;
for (Index = 0; Index <= Expression.Length - 1; Index++)
{
    if (char.IsLetter(Expression[Index]))
    {
        temp = temp + Expression[Index];
    }
    else
    {
        if (temp.Length > 0)
        {
            Variables.Add(temp);
            temp = string.Empty;
        }
    }
}
if (temp.Length > 0)
{
    Variables.Add(temp);
}
foreach (string item in Variables)
{
    Console.WriteLine(item);
}
Console.ReadKey();



我要检测来自表达sin和cos所以我会删除变量sin和cos。

I have to detect SIN and COS from expression so I will remove SIN and COS from Variables.


  1. 是不是好办法?

  2. 是否可以用正则表达式或更好的做到这一点方式?

  3. 此代码是否需要重构?

提取物后,我想替换值的变量从输入和我将计算表达式的结果。

After extract I want replace variables with values from input and I will calculate the expression result.

推荐答案

尝试素描检测表达式的自动机。
之后,实现一个自动机最简单的方法是使用嵌套的if..else一个switch..case。
我认为这将是远比解析字符串你现在的方式更容易

Try sketching an automata that detects expressions. After that the simplest way to implement an automata would be a switch..case with nested if..else. I think it would be far easier than parsing the string the way you are right now.

编辑 -

这是一个很简单的例子,仅用于演示的缘故。假设我要检测VAR1 + VAR2的形式表达,自动机应该是这样的:
图片

This is a very simple example, only for the sake of demonstration. suppose I want to detect expressions in the form of var1 + var2, the automata would look like this: Image

Implementaion看起来是这样的:

Implementaion looks like this:

done = false;
state = start;
while(!done)
{
    switch(state)
    {
    case start:
        if(expression[i] > 'a' && expression[i] < 'z')
            state = start;
        else if(expression[i] == '+')
        {
            // seen first operand and waitng for second
            // so we switch state
            state = add;
        }
        break;
    case add:
        if(expression[i] > 'a' && expression[i] < 'z')
            state = add;
        else
            done = true;
        break;
    }
}



就像我说的这个很简单,你的自动会与更多的国家和过渡更加复杂。我还没有包括在内的行动,但第二个操作数被读取后完成=真后,你可以做实际的加法;

Like I said this is very simple, your automata would be more complex with many more states and transitions. I've also not included actions here, but you could do actual addition after second operand is read which is after done = true;

这篇关于提取字符串数学表达式变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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