The usage of ReverseFind to search for the last character in a string.
The ReverseFind function is used to search for the last occurrence of a specified character or substring in a string and return its position. Its usage is as follows:
int ReverseFind(const char* str, char c);
int ReverseFind(const char* str, const char* subStr);
In this case, str is the string to be searched, c is the character to be found, and subStr is the substring to be found.
Find the last occurrence of a character in a string.
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world!";
char c = 'o';
int pos = str.rfind(c); // 使用rfind函数查找字符
if (pos != std::string::npos) {
std::cout << "Character found at position: " << pos << std::endl;
} else {
std::cout << "Character not found." << std::endl;
}
return 0;
}
Result of running:
Character found at position: 7
Find the last occurrence of a substring in a string.
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world!";
std::string subStr = "world";
int pos = str.rfind(subStr); // 使用rfind函数查找子字符串
if (pos != std::string::npos) {
std::cout << "Substring found at position: " << pos << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
Output result:
Substring found at position: 6
It is important to note that if the specified character or substring cannot be found, the rfind function will return std::string::npos. You can determine whether the character or substring has been found by checking if the position is equal to npos.