Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring from a string in qt?

I have a text form:

Last Name:SomeName, Day:23 ...etc

From Last Name:SomeName, I would like to get Last Name, and separately SomeName.

I have tried to use QRegularExpression,

QRegularExpression re("(?<label>\\w+):(?<text>\\w+)");

But I am getting the result:

QString label = match.captured("label") //it gives me only Name

What I want is whatever text till ":" to be label, and after to be text.

Any ideas?

like image 556
amol01 Avatar asked Apr 12 '14 16:04

amol01


People also ask

How do you substring in 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.

What is QT QString?

QString stores unicode strings. By definition, since QString stores unicode, a QString knows what characters it's contents represent. This is in contrast to a C-style string (char*) that has no knowledge of encoding by itself.

How to initialize a QString?

Initializing a String. One way to initialize a QString is simply to pass a const char * to its constructor.

How do you append in QString?

Try this: double d1 = 0.5,d2 = 30.0 QString str = "abc"; str. append(QString("%1"). arg(d1)); str.


1 Answers

You could use two different methods for this, based on your need:

  • split()
  • section()

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    QString myString = "Last Name:SomeName, Day:23";
    QStringList myStringList = myString.split(',').first().split(':');
    qDebug() << myStringList.first() << myStringList.last();
    return 0;
}

main.pro

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

Build and Run

qmake && (n)make

Output

"Last Name" "SomeName"
like image 164
lpapp Avatar answered Oct 02 '22 01:10

lpapp