C语言之 replace

本文主要针对c++中常用replace函数用法给出样例程序

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. line = line.replace(line.find(“@”), 1, “”);
  5. cout << line << endl;
  6. return 0;
  7. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. line = line.replace(line.begin(), line.begin()+6, “”);
  5. cout << line << endl;
  6. return 0;
  7. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. string substr = “12345”;
  5. line = line.replace(0, 5, substr, substr.find(“1”), 3);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char* str = “12345”;
  5. line = line.replace(0, 5, str);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char* str = “12345”;
  5. line = line.replace(line.begin(), line.begin()+9, str);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char* str = “12345”;
  5. line = line.replace(0, 9, str, 4);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char* str = “12345”;
  5. line = line.replace(line.begin(), line.begin()+9, str, 4);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char c = ‘1’;
  5. line = line.replace(0, 9, 3, c);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

  1. int main()
  2. {
  3. string line = “this@ is@ a test string!”;
  4. char c = ‘1’;
  5. line = line.replace(line.begin(), line.begin()+9, 3, c);
  6. cout << line << endl;
  7. return 0;
  8. }

运行结果:

:所有使用迭代器类型的参数不限于string类型,可以为vector、list等其他类型迭代器。

posted @ 2021-01-12 12:27  Max_hhg  阅读(1338)  评论(0编辑  收藏  举报