string中的npos

STL中的string.find()函数原型如下:

size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_type n) const;
size_t find (char c, size_t pos = 0) const noexcept;

其返回值都是一个size_t类型的。
如果找到就返回该字符或者字符串的下标,如果没找到呢?
STL内使用npos位来标志没找到,先来看看官方如何解释这个变量:

std::string::npos
static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

中文:
size_t的最大值
npos是一个静态成员常量值,其值为size_t类型的元素的最大可能值。

这个值用作字符串成员函数中len(或sublen)参数的值时,意思是“直到字符串结束”。 作为返回值,通常用于表示不匹配。 此常量的值为-1,这是因为size_t是无符号整型,它是此类型最大的可表示值。

使用如下:

std::string s1 = "hello world!";
if(s1.find('o') != std::string::npos){
    std::cout<<"找到字母o"<<    std::endl;
}else{
    std::cout<<"没有找到字母o"<<  std::endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值