The role of string::npos
string::npos 的意思:The constant is the largest representable value of type size_type. It is assuredly larger than max_size(); hence it serves as either a very large value or as a special code.
It roughly means a constant, which is of type size_type and is a very large value
Its role: to indicate a location that does not exist,
Generally, when using find, it is used for judgments that cannot be found.
1 means a very large value, we can look at the following example
#include <iostream>
#include <string>
using namespace std;
int main()
{
size_t aa = -1;
printf("%zu\n",aa);
if (aa == string::npos)
{
printf("相同");
}
};
You can see that aa and string:npos are the same
2 use when find
(find search, return type size_type, which is an unsigned integer (according to the printed one). If the search is successful, return the position of the first character or substring found according to the search rules; if the search fails, return npos)
That is, find returns the coordinates when it finds a match, and returns string::npos when it does not match
In this way, you can use string::npos to judge whether it matches
#include <iostream>
#include <string>
using namespace std;
#include <algorithm>
int main()
{
string str = "hello world";
char ch = 'e';
//查找单个字符
if(str.find(ch)!=string::npos){
cout<<"YES"<<endl;
cout<<str.find(ch)<<endl;
}
else
cout<<"NO"<<endl;
};