使用c ++中的符号分割mathemtical函数

时间:2018-04-23 09:10:25

标签: c++ math split delimiter mathematical-expressions

我想通过其中的变量符号来分割数学函数,如下所示:

string input = x-5y+3z=10

output--> [x,-5y,+3z,=10]

我以前通过使用input.split()函数在java上做这个,但因为我是一个c ++初学者,我找不到像java一样的方法。

任何帮助?

编辑:

经过很长一段时间我找到了我想要的解决方案,也许它不是理想的解决方案,它可以有更多的改进,但正如我之前所说的那样,我仍然是c ++的初学者,这就是它 - >

std::string fun="-x1+2x2=10.";

std::string *arr=new std::string[20];
int index=0;

for (int i=0; i<=20; i++){
    if(fun[index]=='.'){
        break;
    }
    for(int j=index; j<fun.length(); j++){
    if(fun[j]=='+' || fun[j]=='-' || fun[j]=='='|| fun[j]== '.'){
        if(j!=index){
        arr[i]=fun.substr(index,(j-index));
        index=j;
        std::cout<<"term is : "<<arr[i]<<"\t index is : "<<index<<"\t j is : "<<j<<std::endl;
         break;
        }
    }
  }

输出是 - &gt;

term is : -x1    index is : 3    j is : 3
term is : +2x2   index is : 7    j is : 7
term is : =10    index is : 10   j is : 10

如果有任何改进建议,请说。

1 个答案:

答案 0 :(得分:0)

扫描字符串,直至找到'+''-''='之一或到达终点。存储命中的索引(包括0len-1),这将分隔子串。

要处理第一个术语,请注意,如果它有一个符号,第一个子字符串将为空。

x-5y+3z=10
 ^  ^  ^
|x|-5y|+3z|=10|


-x-5y+3z=10
^ ^  ^  ^
||-x|-5y|+3z|=10|