天天看點

(2)string-字元串查找和替換

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

//查找
void test01()
{
	string str = "abcdefghijk";
	int pos = str.find("de");
	if (pos == -1)
	{
		cout << "未找到字元串" << endl;
	}
	else
	{
		cout << "找到字元串,pos = " << pos << endl;
	}

	//rfind 和 find 差別
	//rfind 從右往左查找 find 從左往右查找
	pos = str.rfind("de");
	cout << "pos = " << pos << endl;
}

//替換
void test02()
{
	string str1 = "abcdef";

	//從1号位置起,替換3個字元,替換為“1111”
	str1.replace(1, 3, "1111");
	cout << "str1 = " << str1 << endl;
}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}
           
c++

繼續閱讀