#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
//字符串的替换
/*
语法:replace(string str, string oldstr, string newstr);
参数:
str:在此源字符串进行替换操作
oldstr:被替换的字符串,不能为空串
newstr:替换的字符串,可以为空串,为空串表示在源字符中删除oldstr
返回值:null
注意:
默认str长度小于1000,如否,重新设定设定tmp大小
需要 string
*/
//注意:在输入的时候 同一个字符串中无空格 以空格来分割两个字符串
//第一种替换字符串的方法用C中的strstr 及C++中的substr
void replace(string &str, string oldstr, string newstr){
const char *pos= NULL;
while ((pos=strstr(str.c_str(), oldstr.c_str()))!=NULL){
int p = pos - &str[0];
int oldlen = oldstr.size();
//截取并替换
str = str.substr(0, p) + newstr + str.substr(p + oldlen);
}
}
//第二种替换字符串的方法用replace()
void string_replace(string&s1, const string&s2, const string&s3)
{
string::size_type pos = 0;
string::size_type a = s2.size();
string::size_type b = s3.size();
while ((pos = s1.find(s2, pos)) != string::npos)
{
//调用string自身的替换函数
s1.replace(pos, a, s3);
pos += b;
}
}
//测试函数
int main(){
string s1, oldstr, newstr;
while (cin>>s1>>oldstr>>newstr){
//replace(s1, oldstr, newstr);
string_replace(s1, oldstr, newstr);
cout << s1 << endl;
}
return 0;
}
C++实现——字符串替换
最新推荐文章于 2024-07-25 09:44:13 发布