ready codes

What is npos ? std::string::npos meaning in C++

Syntax :

static const size_t npos = -1;

What is string::npos

Npos is a constant static member value that has the highest value possible for the type size_t element (Actually, it means until the string’s end ).

  • In the member functions of the string, the value for a length parameter is string::npos.
  • It is typically used as a return value to denote that there are no matches.
  • When used as the value for a len parameter in a member function for a string, npos denotes the length of the string. The definition of this constant uses the value -1. The largest representable value for size_t is -1 because it is an unsigned integral type.


Simply put, consider npos to be no-position. It is typically used as a return value to say that the string contained no matches. If it returns true, it means that no matches were discovered at any places.

Code using string::npos in C++

#include <iostream>
using namespace std;

int main() {
  string str2 = "app";
  string str = "an apple";
  int found=str.find(str2);

  if (found != string::npos){
    cout << "first 'app' found at: " << int(found) << endl;

Output :

first 'app' found at: 3
Back to top button