What is string::npos in C++?

svg viewer

npos is a constant static member value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len parameter in string’s member functions, means until the end of the string. This constant is defined with a value of -1. Since size_t is an unsigned integral type, -1 is the largest possible representable value for this type.

To put it simply, think of npos as no-position. As a return value, it is usually used to indicate that no matches were found in the string. Thus, if it returns true, matches were found at no positions (i.e., no matches).

Code

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

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved