Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::basic_string::npos — not found or through the end

Test a `find` result against `npos` before using it as an index. In the count parameter of `substr`, the same constant means to take the rest of the string.

Version: ISO C++23; implementation support may vary

Syntax

static constexpr size_type npos = size_type(-1); // member of std::basic_string in <string>
std::basic_string<CharT, Traits, Allocator>::npos
std::string::npos // for std::basic_string<char>

std::basic_string::npos is a static constexpr member declared in <string>. The initializer size_type(-1) converts -1 to the largest value of the specialization’s unsigned size_type. It is not a negative number or the current size(). For std::string, write std::string::npos.

find returns the zero-based index of the first match or npos if there is no match. Keep the result in auto or size_type, not int, and test it against npos before indexing or computing pos + 1. If a separator is required, reject the record when it is missing. By contrast, the default pos = npos for rfind puts no upper bound on the match position; a returned npos still means no match.

In substr(pos, count), the default count = npos means “from pos through the end.” An oversized count is limited to size() - pos, but pos > size() throws std::out_of_range; pos == size() gives an empty string. In C++23, both the const & and && overloads of substr return an owning string, not a view.

“Through the end” also applies to append(src, pos, n) and assign(src, pos, n) with a basic_string source. In contrast, append(ptr, n) and assign(ptr, n) require an actual count of elements available through the pointer. Do not pass npos as a buffer length. When supplying data() and size() to a pointer-and-length receiver, check its range and lifetime requirements.

Examples

#include <iostream>
#include <string>

int main() {
    const std::string records[] = {"mode=fast", "mode"};
    for (const auto& record : records) {
        const auto sep = record.find('=');
        if (sep == std::string::npos) {
            std::cout << "missing '='\n";
            continue;
        }
        const auto key = record.substr(0, sep);
        const auto value = record.substr(sep + 1, std::string::npos);
        std::cout << key << ": " << value << '\n';
    }
}

Result

mode: fast
missing '='

The first record splits into the key `mode` and the value `fast`, printed with a colon. The second record lacks `=`, so the program reports the error before calculating the value’s start position.

Related lessons

  • C++ · Lesson 58 · Advanced · Version: 3

Sources