C++中std::string::npos

std::string::npos是一个常量,表示size_t类型的最大值,常用于表示字符串查找无匹配项的结果或作为长度参数。在示例中,它被用来检查字符串是否包含特定字符并进行替换操作。当find方法找不到匹配项时,返回npos,其值为无符号整数的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载:C++中std::string::npos_VoladorL的博客-CSDN博客

std::string::npos
(1)它是一个常量静态成员值,对于 size_t 类型的元素具有最高可能值。
(2)它实际上意味着直到字符串的末尾。
(3)它用作字符串成员函数中长度参数的值。(4)作为返回值,它通常用于表示没有匹配项。
(5)数据类型为size_t的话string:npos常量被定义为-1,因为size_t是无符号整数类型,-1是该类型的最大可能表示值。

使用示例
作为没有匹配项的示例

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string str = "I am cver";
	size_t index = str.find('.'); 
	if(index == string::npos)
	{
		cout << "This does not contain any period!" << endl;
		cout << index << endl;
	}
		
}

输出

This does not contain any period!
18446744073709551615

作字符串成员函数中长度参数的值

#include <iostream>
#include <string>
using namespace std;
int main()
{
	string str = "I am cver.";
	size_t index = str.find('.'); 
	if(index == string::npos)
	{
		cout << "This does not contain any period!" << endl;
		cout << index << endl;
	}
	else
	{
		str.replace(index, string::npos, "!");
		cout << str << endl;
		cout << index << endl;
	}		
}

输出:

I am cver!
9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值