84

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.

laurent
  • 79,308
  • 64
  • 256
  • 389
AlekseyS
  • 841
  • 1
  • 6
  • 4

2 Answers2

123

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"
αλεχολυτ
  • 4,408
  • 1
  • 23
  • 62
Alan
  • 1,738
  • 1
  • 9
  • 9
  • 1
    In your second example, you can do: QStringRef subString = myString.midRef(5,2); – Keith Jan 31 '13 at 16:49
  • 2
    Note that using `QStringRef` is an optimization that comes with additional complexity. Unless you are doing heavy string manipulations, and you'll actually benefit from the optimization (in most cases, you won't), it's safer and simpler to use a `QString`. – laurent Jun 10 '14 at 02:01
  • But when i want to use to for a qlabel as text, i have to cast it to QString? Or is there a way to directly use QStringRef? – user1767754 Jan 10 '15 at 01:10
  • 1
    @this.lau_ I remember Java substrings all worked this way by default, but later after seeing cases where a small substring of some huge string prevented the huge string from getting garbage collected, they got rid of that behavior. – Andy Jun 12 '15 at 05:12
  • Note that `QStringRef ` as first argument takes pointer to `QString`. – Binary Mind Nov 13 '16 at 22:45
  • 1
    @Andy, in Qt the behaviour is slightly different - the QString that QStringRef is referencing might get deleted, in which case the QStringRef becomes invalid. This is why the additional complexity is often not worth it. To quote the doc: `We suggest that you only use this class in stable code where profiling has clearly identified that performance improvements can be made by replacing standard string operations with the optimized substring handling provided by this class.` – laurent Dec 24 '16 at 08:58
53

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.

laurent
  • 79,308
  • 64
  • 256
  • 389