KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / C++

`std::string::npos`: geen treffer of een aantal tot het einde

Vergelijk het resultaat van `std::string::find` met `std::string::npos`. Als aantal tekens in `substr` of `erase` betekent dezelfde constante ‘tot het einde’, niet een beginpositie.

Versie: 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 here

In C++23 is std::string::npos een static constexpr-lid van het type std::string::size_type, beschikbaar via <string>. De omzetting van -1 naar dit type zonder teken levert de grootste waarde op die het type kan weergeven. Het is geen negatieve index; ga niet uit van een vaste typebreedte of decimale waarde.

input.find('#') kiest de overload voor één teken. Die zoekt standaard vanaf index 0 en geeft de index van de eerste treffer terug, of std::string::npos als er geen treffer is. Bewaar het resultaat met auto of std::string::size_type: pos == std::string::npos betekent geen treffer en pos != std::string::npos betekent wel een treffer. Gebruik niet if (pos): de geldige index 0 is false, terwijl npos true is.

De betekenis hangt af van het argument. s.substr(start, std::string::npos) geeft een aparte string terug vanaf start tot het einde; s.erase(start, std::string::npos) verwijdert dat deel uit s. Bij beide aanroepen mag start niet groter zijn dan s.size(); anders gooit de functie std::out_of_range. Controleer op een treffer voordat je het resultaat als index of beginpositie gebruikt of ermee rekent.

Voorbeelden

#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);
}

Resultaat

Rejected at index 0
Accepted: draft!

In `#draft` staat `#` op index `0`. De functie wijst de invoer af voordat ze de inhoud kopieert of een string wijzigt. In `draft` staat geen `#`; de functie kopieert de invoer en voegt `!` aan de kopie toe, zonder de invoer te wijzigen.

Gerelateerde lessen

  • C++ · Les 15 · Gevorderd · Versie: 3

Bronnen