我正在使用Qt Creator开发一个C++应用程序,我正在尝试学习QString函数,但我在使用indexOf()函数时遇到了问题。我尝试在另一个字符串中查找"str“字符串,但此函数总是返回第一个索引
#include <QString>
#include <QDebug>
int main()
{
QString str = "Topic of today is QString String";
QString y = "Str";
int index;
index = str.indexOf(y, 1);
qDebug() << "index: " << index;
}发布于 2020-12-10 22:02:58
它总是返回第一个索引,因为您使用1作为indexOf()的第二个参数。当您想要第二个匹配时,您需要使用前一个索引作为第二个参数。
下面的代码展示了如何查找和显示前两个匹配项。
#include <QString>
#include <QDebug>
int main()
{
QString str = "Topic of today is QString String";
QString y = "Str";
int index = 0;
index = str.indexOf(y, index);
qDebug() << "First index: " << index;
if (index > 0) {
index = str.indexOf(y, index+1);
if (index > 0) qDebug() << "Second index: " << index;
}
}发布于 2020-12-10 21:59:06
indexOf返回与给定的startfrom偏移量(1)匹配的第一个索引。
如果希望获得所有索引,则需要重复调用indexOf,将startfrom设置为找到的最后一个索引+1,直到不再找到索引为止。
https://stackoverflow.com/questions/65235891
复制相似问题