Qt. get part of QString

QtSubstringQstring

Qt Problem Overview


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.

Qt Solutions


Solution 1 - Qt

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"

Solution 2 - Qt

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlekseySView Question on Stackoverflow
Solution 1 - QtAlanView Answer on Stackoverflow
Solution 2 - QtlaurentView Answer on Stackoverflow