string容器04之string字符串的查找与替换

2021-03-02 16:57:26 浏览数 (1)

string字符串的查找与替换

代码语言:javascript复制
#include<iostream>
using namespace std;
//string字符串的查找与替换
void test() 
{
	
	string s1 = "abc   dhy   defg";
	//查找:
	//find
	int ret = s1.find("dhy");
	if (ret == -1)
	{
		cout << "查到个der" << endl;
	}
	else{
		cout << "ret=" << ret << endl;
	}
	//rfind
	int result = s1.rfind("dhy");
	if (result == -1)
	{
		cout << "查到个der呀!!!" << endl;
	}
	else {
		cout << "result=" << ret << endl;
	}
	//注意find和rfind的区别:find从左往右查找,rfind从右往左查找,都返回字符串从左往右开始第一个下标位置
	//查找不到都返回-1
	//替换:
	//replace  将abc替换成了ly
	s1.replace(0, 3, "ly");
	cout << s1 << endl;
	
}
int main()
{
	test();
	system("pause");
	return 0;
}

0 人点赞