string__npos in C++ with Examples

In this article, we will delve into a specific aspect of string handling in C++: the string::npos constant. string::npos is a static member constant value with the greatest possible value for an element of type size_t. This constant is defined with a value of -1, which, when cast to size_t, gives us the largest possible representation for size_t. In the context of strings in C++, it is generally used to indicate an invalid position.

What is String::npos?

In C++, string::npos is a constant static member of the std::string class that represents the maximum possible value for the size_t type. It is typically used to denote the end of a string or that a substring or character could not be found within another string.

Use Cases of String::npos

One of the primary use cases for string::npos is with the std::string::find function. This function returns the position of the first occurrence of a substring within a string. If the substring is not found, the function returns std::string::npos.


Let's see this in action with a simple C++ example −

#include <iostream>
#include <string>

int main() {
   std::string str = "Hello, World!";
   size_t found = str.find("World");
   if (found != std::string::npos)
      std::cout << "'World' found at: " << found << '\n';
      std::cout << "'World' not found\n";
   found = str.find("Earth");
   if (found != std::string::npos)
      std::cout << "'Earth' found at: " << found << '\n';
      std::cout << "'Earth' not found\n";
   return 0;


'World' found at: 7
'Earth' not found

In this example, the program tries to find the substrings "World" and "Earth" in the string "Hello, World!". For "World", the find function returns the position of the first occurrence, which is 7. For "Earth", the find function returns string::npos because "Earth" is not found in the string, indicating an invalid position.


string::npos is a useful constant for string manipulation in C++, especially when working with functions like find that may return an invalid position. It's important to understand how and when to use string::npos in your C++ programs to handle strings effectively.

Updated on: 18-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started