MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / find_last

Function find_last

Examples/Modules/Chapter 09/Ex9_01.cpp:30–46  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

28}
29
30std::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}

Callers 1

mainFunction · 0.70

Calls 2

emptyMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected