how to search backwards using QString indexOf?

I made a mistake to search backwards with the indexOf function of QString:

QString str="hi, myprogrammingnotes.com is a good place to learn programming knowledge.";

int pos=str.indexOf("good",-1);

I thought the second parameter of indexOf , if set to -1, will instruct the function to search from the last character backwards for the specified pattern. But it always returns -1, meaning the pattern is not found. In fact, I misunderstood the usage of the second parameter of indexOf.  The second parameter is the position to begin the search but not the search direction. indexOf always searches forward, so it can not find the pattern in this case. To search backward, you should use another function lastIndexOf as follows:

int pos= str.lastIndexOf("good",-1);

It will search backward for the pattern from the last character. Note that the second parameter defaults to 0 for indexOf and defaults to -1 for lastIndexOf. So the above statement is equal to:

int pos=str.lastIndexOf("good");

 

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.