C++中string::npos 的使用

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.

大致意思 是一个常量, 是size_type类型,是一个非常大的值

它的作用:表示一个不存在的位置 ,

一般使用find的时候查找不到的判断时候使用.

1 表示一个非常大的值,我们可以看下下面的例子

#include <iostream>
#include <string>
using namespace std;
int main()
{
    size_t aa = -1;
    printf("%zu\n",aa);
    if (aa == string::npos)
    {
      printf("相同");
    }
    
    
};

 可以看到aa 和 string:npos 是相同的

 2 find 的时候使用

(find查找,返回类型size_type,即一个无符号整数(按打印出来的算)。若查找成功,返回按查找规则找到的第一个字符或子串的位置;若查找失败,返回npos)

就是find 查找匹配到的时候返回坐标,匹配不到的时候返回string::npos

这样就可以使用string::npos 判断是否匹配到了

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

猜你喜欢

转载自blog.csdn.net/qq_33210042/article/details/130885642