PDA

View Full Version : searching a QString in a QStringList



Alex22
21st January 2016, 14:10
Hi,
There is a QStringList with "n" fields. I want to search a QString in all items of the QStringList and item at index position "i" must be returned. Case Sensitive is not important. even if that QString be inside in an item, that item must be returned.

for example:



QStringList list;
list<< "Hello" << "lombo" << "Hi" << "hlok";
//I want to search "lo" and need to find this in: "Hello", "lombo", "hlok" and returned items at index position 0, 1, 3


Thanks for any help

Lesiok
21st January 2016, 15:39
Read about QStringList::indexOf methods.

Alex22
21st January 2016, 16:10
Thanks Lesiok,
I used:


QStringList list;
list << "hello" << "heeeeee"<<"he" << "kreo" << "gry" << "hhh";

qDebug() << list.indexOf(QRegExp("he", Qt::CaseInsensitive, QRegExp::W3CXmlSchema11), 0);//I checked all of PatternSyntax but for all, it returns 2


but always returns 2. I need it returns 0 because "he" exists in "hello" too.

Lesiok
21st January 2016, 16:20
I think that it should be something like that
list.indexOf(QRegExp(".*he.*", Qt::CaseInsensitive, QRegExp::W3CXmlSchema11), 0)or simpler
list.indexOf(QRegExp("*he*", Qt::CaseInsensitive, QRegExp::Wildcard), 0)

Alex22
21st January 2016, 16:33
Lesiok, Thanks in advance


QStringList list;
list <<"dcsdcsdcscsc"<<"jjjjj" <<"hghghghegggg"<<"hello" << "heeeeee"<<"he" << "kreo" << "gry" << "hhh";

for(int i=0; i<9; i++)
{
if(list.indexOf(QRegExp("*he*", Qt::CaseInsensitive, QRegExp::Wildcard), i)-i == 0)
qDebug() <<list.indexOf(QRegExp("*he*", Qt::CaseInsensitive, QRegExp::Wildcard), i);
}


works well.

Lesiok
21st January 2016, 20:41
Optimal code looks like this

QStringList list;
list <<"dcsdcsdcscsc"<<"jjjjj" <<"hghghghegggg"<<"hello" << "heeeeee"<<"he" << "kreo" << "gry" << "hhh";

for(int i=0; i<list.size(); i++)
{
i = list.indexOf(QRegExp("*he*", Qt::CaseInsensitive, QRegExp::Wildcard), i);
if( i < 0 )
break;// QStringList::indexOf returns -1 if not found

qDebug() << i;
}

yeye_olive
22nd January 2016, 10:19
Even more optimized code would avoid recomputing the QRegExp and list.size() on each iteration of the loop.