| 28 | } |
| 29 | |
| 30 | std::optional<size_t> find_last(const std::string& string, char to_find, |
| 31 | std::optional<size_t> start_index) |
| 32 | { |
| 33 | // code below will not work for empty strings |
| 34 | if (string.empty()) |
| 35 | return std::nullopt; // or: 'return std::optional<size_t>{};' |
| 36 | // or: 'return {};' |
| 37 | // determine the starting index for the loop that follows: |
| 38 | size_t index{ start_index.value_or(string.size() - 1) }; |
| 39 | |
| 40 | while (true) // never use while (index >= 0) here, as size_t is always >= 0! |
| 41 | { |
| 42 | if (string[index] == to_find) return index; |
| 43 | if (index == 0) return std::nullopt; |
| 44 | --index; |
| 45 | } |
| 46 | } |