F.Bartos
F.Bartos

Reputation: 53

Qt- Splitting strings but keep the delimiters in array

I am trying to split string using delimiters but I want to keep the delimiters in the array. Code :

QRegExp rx("(\\+|\\-|\\*|\\/)");
QStringList query = text.split(rx);

Input:

2+3

This will give me an array 2,3 but I want 2,+,3

Is there any way to do that ?

Upvotes: 0

Views: 855

Answers (2)

Praveen Kumar
Praveen Kumar

Reputation: 483

You can have a work around solution for your problem. Try this code :

#include <iostream>
#include <QStringList>
#include <QRegExp>

int main()
{
    QString text = "2+3-3-4/5+9+0"; // Input, you can write you own code to take input
    QRegExp rx("(\\+|\\-|\\*|\\/)");
    QStringList query = text.split(rx);

    int count = 0;
    int pos = 0;
    while ((pos = rx.indexIn(text, pos)) != -1) {
        ++count;
        pos += rx.matchedLength();
        query.insert(count * 2-1, QString(text[pos - 1]));
    }
    return 0;
}

Upvotes: 1

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126085

I don't think there's a function in Qt that does it for you, but you could easily reconstruct it. Pseudo code, because I don't know the exact syntax:

QStringList query = text.split(rx);
QStringList queryWithSeparators;

size_t pos = 0;
for (const auto part : query) {
    queryWithSeparators.append(part);
    pos += part.length;

    if (pos + 1 < text.length) {
        // we know that the separators are all 1 character long
        queryWithSeparators.append(text.substring(pos, 1));
        pos += 1;
    }
}

This is ugly and difficult to understand. From you example it seems that you are trying to parse a mathematical expression. It's much easier to create a tokenizer which reads character-by-character than trying to use regular expressions for this task.

(If you really want to use split, you could first split it for all +, then split these strings at all - etc. This way you would know exactly what the separators are.)

Upvotes: 0

Related Questions