To begin with, the std::string
interface is well known to be bloated and inconsistent, see Herb Sutter’s Gotw84 on this topic. But nevertheless, there is a reasoning behind std::string::find
returning an index: std::string::substr
. This convenience member function operates on indices, e.g.
const std::string src = "https://stackoverflow.com/questions/58430288/abcdefghijk";
std::cout << src.substr(2, 5) << "\n";
You could implement substr
such that it accepts iterators into the string, but then we wouldn’t need to wait long for loud complaints that std::string
is unusable and counterintuitive. So given that std::string::substr
accepts indices, how would you find the index of the first occurence of 'd'
in the above input string in order to print out everything starting from this substring?
const auto it = src.find('d'); // imagine this returns an iterator
std::cout << src.substr(std::distance(src.cbegin(), it));
This might also not be what you want. Hence we can let std::string::find
return an index, and here we are:
const std::string extracted = src.substr(src.find('d'));
If you want to work with iterators, use <algorithm>
. They allow you to the above as
auto it = std::find(src.cbegin(), src.cend(), 'd');
std::copy(it, src.cend(), std::ostream_iterator<char>(std::cout));