std::string::npos的使用

std::string::npos

std::string::npos是一个常数,它等于size_type类型可以表示的最大值,用来表示一个不存在的位置,类型一般是std::container_type::size_type。

定义

static const size_type npos = -1;

#include <iostream>

int main(int argc, char *argv[]) {
	size_t a = -1;
	std::cout << "a : " << a << std::endl;
	std::cout << "npos : " << std::string::npos << std::endl;
	std::cout << "size_type max : " << std::numeric_limits<std::string::size_type>::max() << std::endl;
	std::cout << "size_t max : " << std::numeric_limits<size_t>::max() << std::endl;
	std::cout << "uint64_t max : " << std::numeric_limits<uint64_t>::max() << std::endl;
	return 0;
}

执行结果

a : 18446744073709551615
npos : 18446744073709551615
size_type max : 18446744073709551615
size_t max : 18446744073709551615
uint64_t max : 18446744073709551615

使用

std::string的查找函数
  1. find
  2. rfind
  3. find_first_of
  4. find_first_not_of
  5. find_last_of
  6. find_last_not_of
    这些操作全都返回 string::size_type 类型的值。
example
#include <iostream>

int main(int argc, char *argv[]) {
	std::string const s = "This is a string";
	
	std::string::size_type n1 = s.find("is");
	if (std::string::npos == n1) {
		std::cout << "not found is" << std::endl;
	} else {
		std::cout << "index : " << n1 << std::endl;
	}
	
	std::string::size_type n2 = s.find("oo");
	if (std::string::npos == n2) {
		std::cout << "not found oo" << std::endl;
	} else {
		std::cout << "index : " << n2 << std::endl;
	}
	
	return 0;
}

执行结果

index : 2
not found oo
  • 14
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值