string s = "I Like C++ Tutorial";
cout << s.find_last_of("Like");
I know that find_last_of returns the last character that matches, however, it returns 16
, which is the position of the letter i
in Tutorial
, But I'm confused because I'm searching for the last position of Like
not i
, I tried to remove i
from the string. It returns 5
as I expected. But the question is why did it return 16
?
std::find_last_of
Finds the last character equal to one of characters in str
this means when searching the string "I Like C++ Tutorial" for the string "Like" the last character that apears in both strings is "i" wich is at position 16.
when searching for a complete string use std::find
std::string s("I Like C++ Tutorial");
std::cout << s.find("Like"); // prints 2
if you want to find the last occurence of the string use std::rfind
std::string s("I Like C++ Tutorial Like");
std::cout << s.rfind("Like"); // prints 20
to get the position of the last character in the last match you just have to add the length of the string:
std::string s("I Like C++ Tutorial Like");
std::string s2("Like");
std::cout << s.rfind(s2) + s2.length(); // prints 24
find_last_of
finds the last character equal to one of characters in the given character sequence.
The character sequence is "Like"
. The last L
is at position 3
, the last i
is at position 16
, the last k
is at position 4
and the the last e
is at position 5
. So it returned the 16
, the greatest of these values.
If the character sequence was "like"
instead of "Like"
, it would have returned 18
because the last l
is at position 18
.
In case no letter in the character sequence that matches any letter in the string, npos
is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With