Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 414
Phorskin Avatar asked Nov 03 '14 21:11

Phorskin


People also ask

How to split QString in Qt?

To break up a string into a string list, we used the QString::split() function. The argument to split can be a single character, a string, or a QRegExp. To concatenate all the strings in a string list into a single string (with an optional separator), we used the join() function.

How do I get substring from QString?

If you do not need to modify the substring, then you can use QStringRef . The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string.


1 Answers

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"
like image 150
lpapp Avatar answered Sep 30 '22 21:09

lpapp