C语言之 replace
本文主要针对c++中常用replace函数用法给出样例程序
- int main()
- {
- string line = “this@ is@ a test string!”;
- line = line.replace(line.find(“@”), 1, “”);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- line = line.replace(line.begin(), line.begin()+6, “”);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- string substr = “12345”;
- line = line.replace(0, 5, substr, substr.find(“1”), 3);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char* str = “12345”;
- line = line.replace(0, 5, str);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char* str = “12345”;
- line = line.replace(line.begin(), line.begin()+9, str);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char* str = “12345”;
- line = line.replace(0, 9, str, 4);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char* str = “12345”;
- line = line.replace(line.begin(), line.begin()+9, str, 4);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char c = ‘1’;
- line = line.replace(0, 9, 3, c);
- cout << line << endl;
- return 0;
- }
运行结果:
- int main()
- {
- string line = “this@ is@ a test string!”;
- char c = ‘1’;
- line = line.replace(line.begin(), line.begin()+9, 3, c);
- cout << line << endl;
- return 0;
- }
运行结果:
注:所有使用迭代器类型的参数不限于string类型,可以为vector、list等其他类型迭代器。