21C++ 16.2.4 在string中查找字符或字符串

在string中查找字符或字符串

程序清单16.4

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

int main(){
	string s = "You can do it!";
	
	//find substring "it" from position 0
	int p1 = s.find("it", 0); 
	
	//use string::npos check if substring was founded
	if(p1 != string::npos)
		cout << "its position is " << p1 << endl;
	else 
		cout << "not found" << endl;
	
	//find character 
	int p2 = s.find('Y', 0);
	if(p2 != string::npos)
		cout << "its position is " << p2 << endl;
	else 
		cout << "not found" << endl;
	
	//多次查找 o
	int p3 = s.find('o', 0);
	if(p3 != string::npos)
		do{
			cout << "its position is " << p3 << endl;
			p3 = s.find('o', p3+1);
		}while(p3 != string::npos);
	else
		cout << "not found" << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值