std::basic_...iew::substr(3)
π NAME π
std::basic_string_view::substr β yep, bestie, it's literally std::basic_string_view::substr. The page header calls this one std::basic_...iew::substr(3) from the C++ Standard Libary (that spelling is the page's, not mine π), and it's the member that hands you a substring view.
β¨ Synopsis β¨
Okay so here's the whole signature, and yes it's constexpr:
constexpr basic_string_view substr( size_type pos = 0,
size_type count = npos ) const;
since C++17 β it's giving modern-standard energy, no cap.
It returns a view of the substring [pos, pos + rlen), where rlen is the smaller of count and size() - pos. Slicey. Iconic. Periodt. π
πΈ Parameters πΈ
posβ position of the first character.countβ requested length.
π¦ Return value π¦
View of the substring [pos, pos + rlen). That's the whole vibe. π
π Exceptions π
std::out_of_range if pos > size().
fr fr, ifposis bigger thansize(), it throwsstd::out_of_rangeβ do not test that boundary unless you're ready for the drama.
β‘ Complexity β‘
Constant. Literally constant. Effortless. β¨
π» Example π»
// Run this code
#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, i.e. data[0, 5] that is [0, 6)
std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF, i.e. [1, 6)
std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE, i.e. [2, 2 + 3)
std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF, i.e. [4, 6)
try
{
[[maybe_unused]]
auto sub = 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)
π See also π
copyβ copies characters (public member function).findβ find characters in the view (public member function).substrβ returns a substring (public member function ofstd::basic_string<CharT,Traits,Allocator>).
okay bye bestie π«Ά this page is from source http://cppreference.com, date/version 2024.06.10, and the manual name is std::basic_...iew::substr(3). Slay and stay safe out there πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms