string::npos in C++

In this tutorial, We are going to learn about the string:: npos using C++. Let us know more about it.

What is string::npos?

It is a static member value with the maximum value for an element of type size_t which is the end of the string. As the Return value indicates no matches are found in the string. It simply states “no-position”. Below is the Syntax for using this

static const size_t npos = -1;

 

Let us see some examples to have a better understanding of the question.

Let us take an input of two strings 
str1= "an apple"
str2 = "app"
 
So the output first 'app' found at Index 3

IMPLEMENTATION OF THE CODE FOR string::npos

// Importing Header files
#include <bits/stdc++.h>
using namespace std;
 
// Function that using string::npos for finding positions
void fun(string s1, string s2)
{
    // Find position of string s2
    int found = s1.find(s2);
 
    // Check the position 
    if (found != string::npos) {
 
        cout << "first " << s2 << " found at: " << (found) << endl;
    }
 
    else
        cout << s2 << " is not in"
             << "the string" << endl;
}
 
// Driver Code
int main()
{
    // Given strings
    string s1 = "An Apple a day keeps Doctor away";
    string s2 = "App";
  
 
    // Function Call
    fun(s1, s2);
 
    return 0;
}

OUTPUT

First App is found at 3

Leave a Reply

Your email address will not be published.