find/rfind/substr的基本用法

string的查找
find/rfind函数可以传三种东西
1.字符
2.字符串
3.字符容器
find是从前面开始找
rfind是从后面开始找
缺省参数:
从什么位置开始找
找到了返回下标,找不到返回-1.但是由于返回值的类型是unsigned类型,所以打印出来就成了4294967295.
getline是为了解决cin输入字符串碰到空格就的问题,getline碰到回车才会停`

#include<string>
using namespace std;
int main()
{
	//
	string str = "123456123456123456";
	cout << str << endl << "0123456789abcdefghj" << endl; //方便查看"123456123456123456"的下标位置
	//int pos = str.rfind("123");   
	//cout << pos << endl;
	//int pos = str.rfind("456", 12);//有匹配项时向前寻找,返回下标值
	//cout << pos << endl;
	//int pos = str.rfind("456", 2); //无匹配值时向前寻找,找不到的话下标值返回-1;
	//int pos = str.find("456"); //	是从字符串的左侧开始匹配str的,并返回在字符串中的位置
	//int pos = str.find("456", 3);	//find("str",pos);从pos开始向左寻找看有无匹配项,有则返回下标值,无则返回-1;
	//int pos = str.find("123", 14);
	//cout << pos << endl;
	//substr的目的是生成子串
	//substr的基本语法:string substr(size_t pos=0,size_t)
	system("pause");
	return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str = "abcdefgh";
	string cpstr;
	//str.substr(a)截取str里面从a开始之后的字符组成的字符串
	cpstr = str.substr(5);
	cout << cpstr << endl;
	string cpstr2;
	//str.substr(a,b)截取str里面a开始之后的b个字符组成的字符串.
	cpstr2 = str.substr(4, 2);
	cout << cpstr2 << endl;
	cout << str.substr(-5, 1) << endl;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值