CKTIS / C++
`std::string::npos`: no match or a count to the end
Compare the result of `std::string::find` with `std::string::npos`. As a count in `substr` or `erase`, the same constant means “through the end,” not a starting position.
Version: ISO C++23; implementation support may vary
Syntax
#include <string>
// Declaration inside std::basic_string in C++23:
// static constexpr size_type npos = size_type(-1);
// For an existing std::string s:
// const auto pos = s.find('#');
// pos == std::string::npos // no match
// pos != std::string::npos // match found
// s.substr(0, std::string::npos) // npos is a count hereIn C++23, std::string::npos is a static constexpr member of type std::string::size_type, available through <string>. Converting -1 to this unsigned type yields its largest representable value. It is not a negative index; do not assume a particular type width or decimal value.
input.find('#') selects the single-character overload. By default it searches from index 0 and returns the index of the first match or std::string::npos if none exists. Keep the result in auto or std::string::size_type: pos == std::string::npos means no match, and pos != std::string::npos means a match was found. Do not use if (pos): the valid index 0 is false, while npos is true.
The argument determines the meaning. s.substr(start, std::string::npos) returns a separate string from start through the end; s.erase(start, std::string::npos) removes that portion from s. In both calls, start must not exceed s.size(), or the function throws std::out_of_range. Check for a match before using the search result as an index or starting position or doing arithmetic with it.
Examples
#include <iostream>
#include <string>
void process(const std::string& input)
{
const auto pos = input.find('#');
if (pos != std::string::npos) {
std::cout << "Rejected at index " << pos << '\n';
return;
}
std::string result = input;
result += '!';
std::cout << "Accepted: " << result << '\n';
}
int main()
{
const std::string invalid = "#draft";
const std::string valid = "draft";
process(invalid);
process(valid);
}
Result
Rejected at index 0 Accepted: draft!
In `#draft`, `#` is at index `0`, so the function rejects the input before copying its contents or modifying a string. In `draft`, there is no `#`; the function copies the input and appends `!` to the copy, leaving the input unchanged.
Related lessons
- C++ · Lesson 15 · Advanced · Version: 3
Sources
- C++23 working draft N4950 — [basic.string], [string.find], [string.view.find], [string.substr], [string.cons], [string.erase], [conv.integral]
- [basic.string] — Class template basic_string
- [string.find] — basic_string searching
- [string.view.find] — basic_string_view searching
- [string.substr] — basic_string::substr
- [string.erase] — basic_string::erase