关于find()函数及npos


npos类型: static const size_t npos = -1; 


find()类型声明:

string (1)
size_t find (const string& str, size_t pos = 0) const;
c-string (2)
size_t find (const char* s, size_t pos = 0) const;
buffer (3)
size_t find (const char* s, size_t pos, size_t n) const;
character (4)
size_t find (char c, size_t pos = 0) const;

用法示例:

#include <iostream> 
#include <string> 
using namespace std;

int main (){
	string str ("There are two needles in this haystack with needles.");
	string str2 ("needle");
	// different member versions of find in the same order as above:
	//1
	size_t found = str.find(str2);
	if (found!=string::npos)
	cout << "first 'needle' found at: " << found << '\n';

	//3
	found=str.find("needles are small",found+1,6);
	//从上次找到的位置的下一个位置开始查找 "needles are small"的前六个字符 
	if (found!=string::npos)
	cout << "second 'needle' found at: " << found << '\n';
	
	//2
	found=str.find("haystack");
	if (found!=string::npos)
	cout << "'haystack' also found at: " << found << '\n';
		
	//4
	found=str.find('.');
	if (found!=string::npos)
	cout << "Period found at: " << found << '\n';
	// let's replace the first needle:
	str.replace(str.find(str2),str2.length(),"preposition");
	//从str.find(str2)开始  str2.length()长度 的string串被替换为 "preposition"
	cout << str << '\n';
	return 0;
}


运行结果:




参考:

http://www.cplusplus.com/reference/string/string/find/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值