Skip to content
Related Articles
Open in App
Not now

Related Articles

string::npos in C++ with Examples

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Aug, 2022
Improve Article
Save Article

What is string::npos:

  • It is a constant static member value with the highest possible value for an element of type size_t.
  • It actually means until the end of the string.
  • It is used as the value for a length parameter in the string’s member functions.
  • As a return value, it is usually used to indicate no matches.


static const size_t npos = -1;
Where, npos is constant static value with the highest possible value for an element of type size_t and it is defined with -1.

Program 1: Below is the C++ program to illustrate the use of string::npos:


// C++ program to demonstrate the use
// of string::npos
#include <bits/stdc++.h>
using namespace std;
// Function that using string::npos
// to find the index of the occurrence
// of any string in the given string
void fun(string s1, string s2)
    // Find position of string s2
    int found = s1.find(s2);
    // Check if position is -1 or not
    if (found != string::npos) {
        cout << "first " << s2
             << " found at: "
             << (found) << endl;
        cout << s2 << " is not in"
             << "the string" << endl;
// Driver Code
int main()
    // Given strings
    string s1 = "geeksforgeeks";
    string s2 = "for";
    string s3 = "no";
    // Function Call
    fun(s1, s2);
    return 0;



first for found at: 5



Explanation: In the above program string::npos constant is defined with a value of -1, because size_t is an unsigned integral type, and -1 is the largest possible representable value for this type.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!