Wiruspwns
Wiruspwns

Reputation: 1

C++ QT Getting part from QString

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.

Upvotes: 0

Views: 312

Answers (2)

Raydel Miranda
Raydel Miranda

Reputation: 14360

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.

Upvotes: 0

TheDarkKnight
TheDarkKnight

Reputation: 27629

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

Upvotes: 2

Related Questions