qtqstringqregexp

How to split QString and keep the separator in Qt?


I have a QString: "{x, c | 0x01}", and I want to split it to 7 tokens as below:

{
x
,
c
|
0x01
}

What's the best way to do it in Qt?

I tried to use QString::split(QRegExp("[\\{\\},|]")), but it DOES NOT keep the separator in the result.


Solution

  • Maybe this solution can serve you task:

    int main(void) {
        QString str { "{x, c | 0x01}" };
        QRegExp separators { "[\\{\\},|]" };
    
        QStringList list;
        str.replace( " ", "" );
    
        int mem = 0;
        for(int i = 0; i<str.size(); ++i) {
            if(i == str.indexOf(separators, i)) {
                if(mem) list.append(str.mid(mem, i-mem)); // append str before separator
                list.append(str.mid(i, 1));               // append separator
                mem = i+1;
            }
        }
    
        qDebug() << list;
    
        return 0;
    }
    

    Outputs: ("{", "x", ",", "c", "|", "0x01", "}")

    You can eliminate if(mem) but then use list.pop_front(); orlist.removeAll(""); after the for cycle, as first element will be a rubbish "".