STD::STRING::NPOS

This is a static member constant of the std::string class. It is a special constant used to indicate that a search operation within a string has failed. It is defined as the largest possible value of type size_t, and is returned by string functions like .find(), .rfind(), .find_first_of(), and others when the target substring or character is not found. Because it represents a value that is guaranteed to be out of bounds for any string index, npos is a reliable way to check for failed searches. Developers commonly use it in conditional statements to ensure safe string manipulation, such as avoiding undefined behavior when trying to access or erase parts of a string based on a failed search result.

#include <iostream>
#include <string>                         //for string manipulation functions
using namespace std;

int main() 
{
  // Email address
  string email = "[email protected]";

  // Find the position of '@' using find function which we have covered already
  size_t symbolPosition = email.find("@"); //left-to-right search
   
  // Erase the domain after '@'
  //ALT: email.erase(symbolPosition, 12);
  // Check if '@' was found
  if (symbolPosition != string::npos) {
    // Erase everything after '@'
    email.erase(symbolPosition);  // erase from '@' to end
    // Display the username
    cout << "Username: " << email << endl;
  }
  return 0;
}

Last updated