函数说明
Qt中的indexOf()方法功能与C++中find()方法基本相同,基本功能都为查找目标字符串,并返回其所在字符串中的索引,如果未找到则返回-1。与string::find()方法不同的是,indexOf()方法支持是否区分大小写的查找,不过其使用时会出现无效的问题。
我们先看一下官方文档中的说明:
int QString::indexOf(QLatin1String str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
Returns the index position of the first occurrence of the string str in this string, searching forward from index position from. Returns -1 if str is not found.
If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
文档中描述如果cs为Qt::CaseSensitive则区分大小写,否则不区分大小写。看起来似乎与find()一致,但在实际编码中发现,,使用上述方法并不能达到不区分大小写查找的目的。
仔细阅读官方文档,可以发现indexOf()方法有3个参数,尽管第二个参数显示有默认值,但在实际使用中,仍需要为其赋值,不对其赋值会导致搜索是否区分大小写无效。
示例
QString strTmp = "IndexOfTest";
int nPos = strTmp.indexOf("of", 0, Qt::CaseInsensitive);
示例代码运行在Qt Creator 5.14版本下
这篇博客探讨了Qt库中的QString类提供的indexOf()方法与C++标准库中的string::find()方法在功能上的相似性和差异。主要问题在于indexOf()方法在不指定第三个参数时可能出现的大小写敏感性问题。尽管官方文档表明可以设置Qt::CaseInsensitive进行不区分大小写的查找,但在实际使用中可能不起作用。为避免此问题,必须明确指定第三个参数。博客通过示例代码展示了正确的使用方式,并强调了在QtCreator 5.14版本下测试的有效性。
2572

被折叠的 条评论
为什么被折叠?



