find last occurrence of character in string c++
To find the last occurrence of a character in a string in C++, you can use the std::string::rfind()
function. Here are the steps:
- Start by including the necessary header file:
#include <string>
- Declare a string variable and initialize it with the desired string:
std::string myString = "Hello, World!";
- Use the
rfind()
function to find the last occurrence of a character in the string. Pass the character you want to find as an argument to the function:
char target = 'o';
size_t lastIndex = myString.rfind(target);
The
rfind()
function returns the index of the last occurrence of the character in the string. The index is of typesize_t
. If the character is found, it returns the index; otherwise, it returnsstd::string::npos
, which is a special constant indicating "no position".Check if the character was found by comparing the returned index with
std::string::npos
:
if (lastIndex != std::string::npos) {
// Character found
} else {
// Character not found
}
- You can then use the returned index to access the character or perform any further operations you need.
That's it! You have now found the last occurrence of a character in a string in C++.