代码

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //字符串的查找和替换
  5. //函数原型
  6. /*
  7. //字符串的查找
  8. ① int find(const string& str, int pos = 0) const; //查找str第一次出现的位置,从pos开始查找
  9. ② int find(const char *s, int pos = 0) const; //查找s第一次出现的位置,从pos开始查找
  10. ③ int find(const char *s, int pos, int n) const; //从pos位置查找s的前n个字符第一次位置
  11. ④ int find(const char c, int pos, int n)const; //查找字符c第一次出现位置
  12. ⑤ int rfind(const string& str, int pos = npos) const; //查找str最后一次位置,从pos开始查找
  13. ⑥ int rfind(const char *s, int pos = npos) const; //查找s最后一次位置,从pos开始查找
  14. ⑦ int rfind(const char *s, int pos, int n) const; //从pos位置查找s的前n个字符最后一次位置
  15. ⑧ int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置
  16. //字符串替换
  17. ① string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str
  18. ② string& replace(int pos, int n, const shar* s); //替换从pos开始的n个字符为字符串s
  19. */
  20. //字符串的查找
  21. void test01(){
  22. string s1 = "abcdefgde";
  23. //int pos = s1.find("df");//未找到会返回-1
  24. int pos = s1.find("de");
  25. if (pos == -1) {
  26. cout << "未找到字符串" << endl;
  27. }
  28. else {
  29. cout << "pos = " << pos << endl;
  30. }
  31. //find与rfind的区别
  32. //rfind从右往左查找 find从左往右找
  33. pos = s1.rfind("de");
  34. cout << "pos = " << pos << endl;
  35. }
  36. //字符串替换
  37. void test02() {
  38. string s1 = "abcdefg";
  39. //从1号位置起3个字符替换为“1111”
  40. s1.replace(1, 3, "1111");
  41. cout << "s1 = " << s1 << endl;
  42. }
  43. int main() {
  44. test01();
  45. test02();
  46. return 0;
  47. }

运行结果

image.png