std::string_view substr() method
- od C++17
// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;
Returns a view of the substring [ pos, pos + rcount ), where rcount
is std::min(count, size() - pos)
.
Parameters
pos
- position of the first charactercount
- requested length
Return value
View of the substring [ pos, pos + rcount ).
Complexity
Constant - O(1).
Exceptions
Throws std::out_of_range
if pos > size()
.
Example
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string_view>
int main()
{
typedef std::size_t count_t, pos_t;
constexpr std::string_view data{"ABCDEF"};
std::cout << data.substr() << '\n'; // ABCDEF
std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF
std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE
std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF
// count -> 2 == size() - pos == 6 - 4
try {
data.substr(pos_t(666), count_t(1)); // throws: pos > size()
}
catch(std::out_of_range const& ex) {
std::cout << ex.what() << '\n';
}
}
Possible output
ABCDEF
BCDEF
CDE
EF
basic_string_view::substr: __pos (which is 666) > __size (which is 6)
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.