一、基本概念
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函數時,需要特別注意返回的是引用而不是拷貝,防止不必要的錯誤發生。
原創文章,作者:GBCWU,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/370296.html