Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

npos
c++
string

What is string::npos in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

npos
c++
string
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring