Find index of last occurrence of a char in a C++ string
This post will discuss how to find the index of the last occurrence of a char in a C++ string.
1. Using string::rfind
The standard approach to find the index of the last occurrence of a char in a string is using the string::rfind member function. If the character doesn’t occur in the string, the function returns string::npos.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "A,B,C"; char ch = ','; size_t index = str.rfind(ch); if (index != std::string::npos) { std::cout << index << std::endl; // 3 } return 0; } |
2. Using std::find
Alternatively, we can use the std::find algorithm with a reverse iterator and then use the std::distance (or pointer arithmetic) to get the index of the last occurrence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <algorithm> #include <iterator> int main() { std::string str = "A,B,C"; char ch = ','; auto it = std::find(str.rbegin(), str.rend(), ch); std::cout << std::distance(str.begin(), (it + 1).base()) << std::endl; // 3 return 0; } |
3. Using Loop
Finally, we can iterate over the string in reverse order and find the index of the first matching character. This can be done using a regular for-loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "A,B,C"; char ch = ','; int index = -1; for (int i = str.size() - 1; i >=0; i--) { if (str[i] == ch) { index = i; break; } } std::cout << index << std::endl; // 3 return 0; } |
That’s all about finding the index of the last occurrence of a char in a C++ string.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)