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 .
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|