In C++, how does std::string_view::substr differ from std::string::substr, and what goes wrong when find returns npos?
answer
- same name, different return type
- constant time, no allocation
- pos greater than size() throws
- npos + 1 wraps to 0
- remove_prefix trims in place
basics
~20 sstd::string::substr returns a new std::string, copying and possibly allocating; std::string_view::substr returns a view into the same characters in constant time. Both throw std::out_of_range when pos exceeds size(). Unchecked, find's npos plus one wraps to 0 and silently selects the whole line.
solid answer
~40 sThe two functions share a name and arguments but not a result. `std::string::substr(pos, n)` builds a new `std::string`: linear in the length and usually an allocation. `std::string_view::substr(pos, n)` returns `std::string_view(data() + pos, rlen)`, where `rlen` is the smaller of `n` and `size() - pos`: constant time, no allocation, and a view that borrows the same characters. Both throw `std::out_of_range` if `pos > size()`. The parsing trap is `find` returning `npos`, the largest `size_type`: `line.substr(colon + 1)` with `colon == npos` computes `npos + 1`, which wraps to 0 for an unsigned type, so the "value" silently becomes the whole line. Check for `npos` first. For trimming, `remove_prefix` and `remove_suffix` shrink a view in place; passing more than `size()` violates their precondition. C++26 adds `std::string::subview`, which returns a view directly.
code
cpp · 22 lines#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string request = "Host: example.com\r\nAccept */*\r\n"; // line 2 lacks its colon
std::string_view rest = request;
for (auto eol = rest.find("\r\n"); eol != std::string_view::npos; eol = rest.find("\r\n")) {
std::string_view line = rest.substr(0, eol); // no copy: points into request
rest.remove_prefix(eol + 2);
auto colon = line.find(':');
if (colon == std::string_view::npos) { // without this, colon + 1 wraps to 0
std::cout << "malformed [" << line << "]\n";
continue;
}
std::string_view value = line.substr(colon + 1);
while (!value.empty() && value.front() == ' ') value.remove_prefix(1);
std::cout << '[' << line.substr(0, colon) << "] = [" << value << "]\n";
}
}go deeper
Know that a view's substr returns another view without copying, while a string's substr returns a new string.
Explain the exact rules: pos past size throws, the count clamps, and npos plus one wraps to zero, so check find before slicing.
Write zero-copy parsers with substr and remove_prefix that validate every delimiter, and watch auto when a source changes from string to view.
Decide where zero-copy slicing is worth the lifetime coupling, and keep owning copies at the boundary where parsed data leaves the request.
## Same name, different result | | `std::string::substr` | `std::string_view::substr` | |---|---|---| | returns | a new `std::string` | a `std::string_view` into the same characters | | cost | linear in the result length, usually an allocation | constant | | result's lifetime | independent of the source | tied to whoever owns the source's characters | | `pos > size()` | throws `std::out_of_range` | throws `std::out_of_range` | | `n` past the end | clamped to `size() - pos` | clamped to `size() - pos` | The standard specifies the view version directly: with `rlen` the smaller of `n` and `size() - pos`, it returns `basic_string_view(data() + pos, rlen)`. Nothing is copied, which is why a tokenizer or header parser written with views can split a whole request without a single allocation. The flip side is that every piece shares the source's lifetime. Note that `pos == size()` is allowed and yields an empty result; only `pos > size()` throws. ## The npos trap `find` reports "not found" by returning `npos`, which is `size_type(-1)`, the largest value of an unsigned type. Header parsing usually looks like this: ```cpp auto colon = line.find(':'); auto name = line.substr(0, colon); // npos: clamped, so the whole line auto value = line.substr(colon + 1); // npos + 1 wraps to 0: the whole line again ``` For a malformed line `"Accept */*"` with no colon, `colon + 1` is `0` because unsigned arithmetic wraps, so `value` is the entire line and **nothing throws**. The parser silently accepts a header whose name and value are both `"Accept */*"`. In a run on this machine, `line.substr(colon + 1)` returned `[Accept */*]`, while `line.substr(11)` on the 10-character line threw `std::out_of_range`. The rule is short: 1. call `find`; 2. compare the result with `std::string_view::npos` before doing arithmetic on it; 3. only then slice. ## Trimming in place: remove_prefix and remove_suffix A view can also be narrowed without creating a new one: - `remove_prefix(n)` advances the start by `n` and shrinks the length; - `remove_suffix(n)` shrinks the length by `n`; - both require `n <= size()`; violating that is undefined behaviour up to C++23, and C++26 makes it a hardened precondition that a hardened library implementation checks; - neither touches the characters, which belong to the owner. A typical loop trims leading spaces with `while (!v.empty() && v.front() == ' ') v.remove_prefix(1);` and consumes a buffer line by line with `rest.remove_prefix(eol + 2);` after each `"\r\n"`. ## Additions after C++17 - **C++20** added `starts_with` and `ends_with`; **C++23** added `contains`. - **C++26** adds `std::string::subview(pos, n)`, which returns a `std::string_view` directly instead of copying, and an alias `std::string_view::subview` with the same meaning as `substr`. It also adds `operator+` between `std::string` and `std::string_view`, which C++23 rejects. Both compile with this machine's libc++ under `-std=c++2c` and fail under `-std=c++23`. ## Clearer alternatives to substr Many `substr` calls exist only to compare a piece, and each one is a small chance to get the arithmetic wrong: - `line.substr(0, 5) == "Host:"` is clearer as `line.starts_with("Host:")` (C++20), which states the intent and slices nothing; - `name.substr(name.size() - 5) == ".json"` throws `std::out_of_range` when `name` is shorter than 5 characters, because `size() - 5` wraps to a huge position, while `name.ends_with(".json")` just returns `false`; - `line.find("chunked") != npos` reads better as `line.contains("chunked")` (C++23). The same unsigned wraparound that breaks `npos + 1` breaks `size() - n` whenever `n` can exceed the size. ## Choosing which substr you want - Use the view version when the piece is consumed while the source is alive: parsing, comparing, looking up. - Use the string version, or `std::string(view)`, when the piece must outlive the buffer or be modified. - Never mix them up silently: `auto x = s.substr(...)` is a `std::string` when `s` is a string and a view when `s` is a view, so the same line of code has different costs and lifetimes depending on the type of `s`.
- Why is auto part = s.substr(0, 4); risky to change during refactoring?`auto` deduces whatever `substr` returns. If `s` is a `std::string`, `part` is an owning copy; if `s` is later changed to a `std::string_view`, `part` silently becomes a view with the source's lifetime. Code that returned `part` or stored it was safe before and dangles after, with no compile error. Spelling the type, `std::string part = ...`, keeps the copy explicit.
- What does line.substr(0, line.find(':')) return when there is no colon?The whole line. `find` returns `npos`, and `substr` clamps its count to `size() - pos`, so asking for `npos` characters from position 0 yields everything. That is defined behaviour, not an exception, which is exactly why a missing delimiter goes unnoticed unless the code compares the `find` result with `npos` first.
- std::string_view::substr copies the characters like std::string::substr.
- substr(colon + 1) throws when find returned npos.
- substr(pos) with pos equal to size() throws out_of_range.
- remove_prefix on a view erases characters from the owning string.
- A substr longer than the remaining text is an error in both classes.
Assumes C++17 for string_view; contains is C++23, and std::string::subview and string + string_view concatenation are C++26.