C++ QT Getting part from QString

301 views Asked by At

I have custom(dynamic QString) for example something like this 123+555 and i need to get this after +.Also there can be something different then + (/,*,- etc.). My question is how to get part of string after some char.

2

There are 2 answers

2
TheDarkKnight On

Use the split function, which allows you to specify the separator and returns a list of the elements.

QString string("123+555");
QStringList listItems = string.split('+', QString::SkipEmptyParts);
QString finalString = listItems[1];

Alternatively, you can find by index the separating character location and use that with a call to right

0
Raydel Miranda On

Since you're usin Qt, you could try the class: QRegExp.

With such class you could write code like this:

// This code was not tested.
QRegExp rx("(\\d+)(\\+|\\-|\\*|/)(\\d+)");  // Be aware, I recommend you to read the link above in order to see how construct the proper regular expression.
int pos = rx.indexIn("23+344");
if (pos > -1) {
    QString number_1 = rx.cap(1);  // "23"
    QString op       = rx.cap(2);  // "+"
    QString number_2 = rx.cap(3);  // "344"
    // ...
}

This way you don't have to write code to check which of the characters(operators) "+, -, *, /" is present to then perform a split on the string depending on what character was found.