-1

I want to split a mathematical function by the sign of the variables in it like this :

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

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

i used to do this on java by using input.split() function , but because I'm a c++ beginner i cannot find a way to do it like in java.

Any help ?

Edit:

After a long a time i found a solution to what i want , maybe it's not the ideal solution and it could have more improvements but as i said before I'm a still a beginner in c++ ,here is it ->

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

output is ->

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

if there is any advice to improve it please say .

Mohamed Essam
  • 41
  • 1
  • 9
  • Just iterate the input string and whenever you encounter an operator simply extract the operator and the number after it. – DimChtz Apr 23 '18 at 09:15

1 Answers1

0

Scan the string until you find one of '+', '-', '=' or reach the end. Store the indexes of the hits (including 0 and len-1), that will delimit substrings.

To deal with the very first term, just remark that in case it does have a sign, the first substring will be empty.

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


-x-5y+3z=10
^ ^  ^  ^
||-x|-5y|+3z|=10|
  • Could you write the code which do this ?! – Mohamed Essam Apr 24 '18 at 04:23
  • 1
    No one is here to write your code, by the way. So don't ever post such thing without giving any effort. – Sumsuddin Shojib Apr 24 '18 at 04:45
  • I spent more than 2 hours trying to solve it by your suggestions , and i already solve it and i want to post my answer but i can't find a button in this page to do it :) I wanted to see his code to compare my solution to his solution . – Mohamed Essam Apr 24 '18 at 06:08
  • @MohamedEssam: this takes a for loop, a switch statement and an assignment, that's about it. –  Apr 24 '18 at 06:37
  • I guess you don't have enough reputation point yet to submit an answer. If you want to post your code, maybe you can edit your post and append at the end. – Sumsuddin Shojib Apr 24 '18 at 07:44