Qt Split QString once
Asked Answered
A

2

6

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!

Aspirator answered 3/11, 2014 at 21:8 Comment(6)
Okay... what have you tried?Slumberland
Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! Also see how to askDeathful
I went online and searched for it but didnt find something on forums or the qt documentation. It´s more that I want to know if theres a stock/native function that can do what i suggest.Aspirator
Use indexOf to find the first occurrence of "+". Then split the string using mid - mid(0,index) and mid(index+1)Sarcocarp
It doesnt have to be native function to get your job done about anything. You can take the first element from array and join the rest.Marvelmarvella
So much for one-time users who come, and do not follow up anymore... :(Collinear
A
17

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"
Amimia answered 3/11, 2014 at 22:10 Comment(0)
P
1

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"

Passive answered 24/3, 2021 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.