一、基本概念
QString
是Qt中最为常用的字符串类,其中很重要的一个函数是contains
。contains
函数的作用是用于判断字符串是否包含指定的字符串,例如:
QString str = "Hello World";
if(str.contains("World")){
qDebug() << "The string contains World.";
}
可以看到,如果字符串中包含"World",那么打印出"The string contains World."
二、区分大小写
contains
函数默认是区分大小写的,例如:
QString str = "Hello World";
if(str.contains("world")){
qDebug() << "The string contains world.";
}else{
qDebug() << "The string does not contain world.";
}
上述代码的输出是"The string does not contain world.",因为contains
函数默认是区分大小写的。
如果需要让contains
函数不区分大小写,那么可以使用Qt中的Qt::CaseInsensitive
参数,例如:
QString str = "Hello World";
if(str.contains("world", Qt::CaseInsensitive)){
qDebug() << "The string contains world.";
}else{
qDebug() << "The string does not contain world.";
}
上述代码的输出是"The string contains world.",因为contains
函数使用了Qt::CaseInsensitive
参数,即不区分大小写。需要注意的是,参数大小写是有区别的。
三、搜索方向
contains
函数默认是从字符串的开始位置进行搜索的,如果需要改变搜索方向,可以使用Qt中的Qt::BackwardSearch
参数,例如:
QString str = "Hello World";
if(str.contains("llo", Qt::BackwardSearch)){
qDebug() << "The string contains llo.";
}
上述代码的输出是"The string contains llo.",因为contains
函数使用了Qt::BackwardSearch
参数,即从字符串的末尾开始搜索。
四、多个字符串搜索
contains
函数不仅可以用于搜索单个字符串,还可以用于搜索多个字符串。在多个字符串搜索中,可以使用Qt中的QStringList
类,例如:
QString str = "Hello World";
QStringList strList;
strList << "World" << "Qt";
if(str.contains(strList.join('|'))){
qDebug() << "The string contains World or Qt.";
}
上述代码的输出是"The string contains World or Qt.",因为contains
函数使用了QStringList.join
函数,该函数将字符串列表中的所有字符串使用'|'符号连接在一起,变成"World|Qt",然后用于搜索。
五、正则表达式搜索
除了基本字符串搜索,contains
函数还支持正则表达式搜索。在进行正则表达式搜索时,需要使用Qt中的QRegExp
类,例如:
QString str = "Hello World";
QRegExp rx("\\bh\\w*");
if(str.contains(rx)){
qDebug() << "The string contains a word starts with h.";
}
上述代码的输出是"The string contains a word starts with h.",因为contains
函数使用了QRegExp
类实现了正则表达式搜索,找到了包含h开头的单词。
六、引用和拷贝
在使用contains
函数时,需要注意的一点是,contains
函数返回的是QString
类的引用,而不是拷贝。因此,在使用contains
函数时,需要注意不要修改返回的引用对象,否则会影响到原始的QString
字符串。
QString str = "Hello World";
QString subStr = "World";
if(str.contains(subStr)){
subStr = "Qt";
qDebug() << "The string contains World.";
}
qDebug() << str; //输出结果为"Hello World",而不是"Hello Qt"。
七、总结
QString
contains
函数是Qt中非常常用的函数之一,支持区分大小写、搜索方向的改变、多个字符串和正则表达式搜索等功能。在使用contains
函数时,需要特别注意返回的是引用而不是拷贝,防止不必要的错误发生。