C++ std::string::rfind
Find the final separator when a label contains several parts.
A simple example
std::string::rfind
- Start with "aba", looking for a
- Do this Find the last match
- Result Index 2 (zero-based)
#include <iostream>
#include <string>
int main() {
const std::string value = "aba";
const std::string other = "a";
std::cout << (value.rfind(other)) << "\n";
return 0;
}
2
Syntax
value.rfind(other)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonFind the final dot in an archive name
An archive name contains more than one period. Locate the final one before extracting the extension so the earlier punctuation in the basename is preserved.
#include <iostream>
#include <string>
int main() {
const std::string value = "may.bill.pdf";
const std::string other = ".";
std::cout << (value.rfind(other)) << "\n";
return 0;
}
8
The dot before pdf is the last match.
Find the last route separator
A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.
#include <iostream>
#include <string>
int main() {
const std::string value = "A/B/C";
const std::string other = "/";
std::cout << (value.rfind(other)) << "\n";
return 0;
}
3
The final slash comes before stop C.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
These examples use ASCII. Verify offset units and missing-match behaviour before indexing another string.