Solved How to check is there is a string that I want?
-
Hi All,
I'm using qt5.5 on my computer.
I wanna know is there a string that I want in a QString.
After reading some document, I'm using indexof() to do it.I'm using this to get my QString.
QString wifi_ping = "ping -I eth0 www.google.com.tw -c 1"; Process::executeProcessSync(QString("sh"),QStringList()<<"-c"<<wifi_ping,&wifi_message);
This is what I got in my QString.
PING 192.168.120.112 (192.168.120.112) from 192.168.120.115 eth0: 56(84) bytes of data. 64 bytes from 192.168.120.112: icmp_seq=1 ttl=64 time=0.321 ms --- 192.168.120.112 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.321/0.321/0.321/0.000 ms
And I check it in my program like below.
if(wifi_message.indexof("bad")) { qDebug("Failed"); } else if(wifi_message.indexof("ping statistics")) { qDebug("pass"); }
Unfortunately, It will always goes Failed.
And i check the document, I am sure there is no "bad" string.
Why it will show Failed every time?Thanks in Advance!
-
@victor-wang hi,friend,welcome.
int QString::indexOf(const QString &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.
If from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.qDebug() << wifi_message; ///< to see the string content ///< you can to putout the result //qDebug() << wifi_message.indexof("bad"); if(0 <= wifi_message.indexof("bad")){ qDebug("Failed"); }else if(0 <= wifi_message.indexof("ping statistics")){ qDebug("pass"); }
try again.
-
@victor-wang said in How to check is there is a string that I want?:
if(wifi_message.indexof("bad"))
{
qDebug("Failed");
}
else if(wifi_message.indexof("ping statistics"))
{
qDebug("pass");
}your checks are not correct (false-positive)!
In case it doesn't find the string "bad" -1 is returned. In C++ everything that is not equal zero is true when implicitly converted to bool.So your checks should rather look like this:
if(wifi_message.indexof("bad") >= 0) { qDebug("Failed"); } else if(wifi_message.indexof("ping statistics") >= 0) { qDebug("pass"); }
-
@joeQ
Thanks it works now! -
@raven-worx
Thanks it works now!