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");

 

 

Posted in

Comments are closed, but trackbacks and pingbacks are open.