Phorskin
Phorskin

Reputation: 81

Qt Split QString once

I want to split a QString, but according to the documentation, the split function only allows for splitting whenever the character to split at occurs. What I want is to only split at the place where first time the character occurs.

For example:

5+6+7 wiht default split() would end in a list containing ["5","6","7"]

what I want: a list with only two elements -> ["5","6+7"]

Thanks in advance for your answers!

Upvotes: 6

Views: 3893

Answers (2)

AAEM
AAEM

Reputation: 1850

Use indexOf() to find the first occurrence of "+". Then split the string using mid - mid(0,index) and mid(index+1) – credit to "R Sahu"

Upvotes: 1

László Papp
László Papp

Reputation: 53215

There are various ways to achieve this, but this is likely and arguably the simplest:

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    QString string("5+6+7");
    qDebug() << string.section('+', 0, 0) << string.section('+', 1);
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

"5" "6+7"

Upvotes: 17

Related Questions