代码

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //字符串的插入和删除
  5. //函数原型
  6. /*
  7. ① string& insert(int pos, const char* s); //插入字符串
  8. ② string& insert(int pos, const string& str); //插入字符串
  9. ③ string& insert(int pos, int n, char c); //在指定位置插入n个字符c
  10. ④ string& erase(int pos, int n = npos); //删除从Pos开始的n个字符
  11. */
  12. void test01(){
  13. string s1 = "hello";
  14. //插入
  15. s1.insert(1, "222");
  16. cout << "s1 = " << s1 << endl;
  17. s1.insert(1, 3, '3');
  18. cout << "s1 = " << s1 << endl;
  19. //删除
  20. s1.erase(1, 6);
  21. cout << "s1 = " << s1 << endl;
  22. }
  23. int main() {
  24. test01();
  25. return 0;
  26. }

运行结果

image.png

字符串的插入和删除起始下标都是从0开始。