Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt. get part of QString

I want to get QString from another QString, when I know necessary indexes. For example: Main string: "This is a string". I want to create new QString from first 5 symbols and get "This ".
input : first and last char number.
output : new QString.

How to create it ?

P.S. Not only first several letters, also from the middle of the line, for example from 5 till 8.

like image 794
AlekseyS Avatar asked Sep 28 '11 14:09

AlekseyS


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.

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.

What is 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 do you initialize QString?

Generally speaking: If you want to initialize a QString from a char*, use QStringLiteral . If you want to pass it to a method, check if that method has an overload for QLatin1String - if yes you can use that one, otherwise fall back to QStringLiteral .


2 Answers

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. E.g.

QString myString("This is a string"); QStringRef subString(&myString, 5, 2); // subString contains "is" 

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string"); QString subString = myString.mid(5,2); // subString contains "is" subString.append("n't"); // subString contains "isn't" 
like image 60
Alan Avatar answered Sep 18 '22 17:09

Alan


Use the left function:

QString yourString = "This is a string"; QString leftSide = yourString.left(5); qDebug() << leftSide; // output "This " 

Also have a look at mid() if you want more control.

like image 29
laurent Avatar answered Sep 18 '22 17:09

laurent