代码
#include<iostream>#include<string>using namespace std;//字符串的查找和替换//函数原型/*//字符串的查找① int find(const string& str, int pos = 0) const; //查找str第一次出现的位置,从pos开始查找② int find(const char *s, int pos = 0) const; //查找s第一次出现的位置,从pos开始查找③ int find(const char *s, int pos, int n) const; //从pos位置查找s的前n个字符第一次位置④ int find(const char c, int pos, int n)const; //查找字符c第一次出现位置⑤ int rfind(const string& str, int pos = npos) const; //查找str最后一次位置,从pos开始查找⑥ int rfind(const char *s, int pos = npos) const; //查找s最后一次位置,从pos开始查找⑦ int rfind(const char *s, int pos, int n) const; //从pos位置查找s的前n个字符最后一次位置⑧ int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置//字符串替换① string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str② string& replace(int pos, int n, const shar* s); //替换从pos开始的n个字符为字符串s*///字符串的查找void test01(){ string s1 = "abcdefgde"; //int pos = s1.find("df");//未找到会返回-1 int pos = s1.find("de"); if (pos == -1) { cout << "未找到字符串" << endl; } else { cout << "pos = " << pos << endl; } //find与rfind的区别 //rfind从右往左查找 find从左往右找 pos = s1.rfind("de"); cout << "pos = " << pos << endl;}//字符串替换void test02() { string s1 = "abcdefg"; //从1号位置起3个字符替换为“1111” s1.replace(1, 3, "1111"); cout << "s1 = " << s1 << endl;}int main() { test01(); test02(); return 0;}
运行结果
