获取 QString 的一部分

我想从另一个 QString中得到 QString,当我知道必要的索引时。 例如: 主要字符串: “这是一根绳子”。 我想创建新的 QString从前5个符号,并得到 “这个”
输入: 第一个和最后一个字符号。
输出: new QString

如何创造它?

不仅仅是前几个字母,还有从行的中间,例如从5到8。

184413 次浏览

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.

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"