Solved How to save the split string ?
-
How to get SL1 ?
QString s = ui->lineEdit->text(); // s = "1+2-3×4÷5" ; QStringList SL = s.split(QRegExp("+|-|×|÷")); // QStringList SL1 = ["+", "-", "×", "÷"] float result = 0; for(int i=0; i<SL.length(); i++){ result += SL.at(i).toFloat(); qDebug() << SL.at(i) << SL.at(i).toFloat(); } ui->label->setText(QString::number(result));
-
If you just want the easy way you can do:
QString s = ui->lineEdit->text(); QRegularExpression expr1("[+-×÷]"); QRegularExpression expr2("[^+-×÷]"); QStringList SL = s.split(expr1, QString::SkipEmptyParts); QStringList SL1 = s.split(expr2, QString::SkipEmptyParts); qDebug() << SL; qDebug() << SL1; float sum = std::accumulate(SL.cbegin(), SL.cend(), .0f, [](float val, const QString& str) { return val + str.toFloat(); }); ui->label->setText(QString::number(sum));
If you care about performance you can replace the regular expression with
std::find_any_of
in a loop until you reach the end.Btw. if you don't need to save those sting lists you should prefer
splitRef()
instead ofsplit()
to avoid unnecessary copies. -
QString s = ui->lineEdit->text(); QStringList SL = s.split(QRegExp("[+-×÷]")); QStringList SL1 = s.split(QRegExp("[^+-×÷]"), QString::SkipEmptyParts); float result = SL.at(0).toFloat(); for(int i=1; i<SL.length(); i++){ if(SL1.at(i-1) == "+"){ result += SL.at(i).toFloat(); }else if(SL1.at(i-1) == "-"){ result -= SL.at(i).toFloat(); }else if(SL1.at(i-1) == "×"){ result *= SL.at(i).toFloat(); }else if(SL1.at(i-1) == "÷"){ result /= SL.at(i).toFloat(); } } ui->label->setText(QString::number(result));
It can calculate now, but can only calculate from left to right, can not calculate ×÷ before +-.
-
If you want to have a fully working expression evaluator a simple if/else is not gonna be enough.
To process it left to right you would have to turn your infix notation into the Reverse Polish notation, i.e. arguments followed by the operator
Another way is to build an Abstract Syntax Tree and process that.
To turn infix notation into RPN or AST you can use one of the popular algorithms, e.g. Shunting-yard algorithm.
In any case you're kinda re-inventing a wheel. If you want scripting like that maybe you should look into some existing expression parsers.
-
QStringList SL1 = s.split(QRegExp("[^+-×÷]"), QString::SkipEmptyParts);
Can not split 1+-2
-
@sonichy It does split it, but to parse it correctly you'd need to do another pass and detect that special case. You will also need that for parenthesis and other stuff. Like I said, a full expression parsing is a lot more involved than simple split + for loop.