编写函数将string里的特定子字符串替换为新值
#include"stdafx.h"
#include<iostream>
#include<string>
//#include "ProgramRunClock.h"
//#include<vector>
//#include<list>
//#include<time.h>
using namespace std;
/*void replaceVal(string &s,const string oldVal,const string newVal)
{//使用find方法的,find找子串返回一个下标值,相同的第一个字符的位置
if(*(s.end()-1)!='.')s.push_back('.');
size_t index = s.find(oldVal);
while (index!= s.npos)
{
s.erase(index, oldVal.size());
s.insert(index,newVal);
index = s.find(oldVal);
}
}*/
/*void replaceVal(string &s,const string oldVal,const string newVal)
{
string::size_type sLength = s.size(), oldLength = oldVal.size(), newLength = newVal.size();
if (s[sLength - 1] != '.')s.push_back('.');
for (size_t index = 0; index != sLength; index++)
{//使用下标和substr切割子串比较的方法
if (s.substr(index, oldLength) == oldVal)
{
s.erase(index,oldLength);
s.insert(index,newVal);//插入字符串需要size_t类型参数
}
}
}*/
/*void replaceVal(string &s, const string oldVal, const string newVal)
{
if (*(s.end() - 1) != '.')s.push_back('.');
string::iterator itr;
for (itr = s.begin(); itr != s.end()-oldVal.size()-1; itr++)
{//迭代器与构造临时比较字符串
string temp(itr,itr+oldVal.size());
if (temp == oldVal)
{
s.erase(itr,itr+oldVal.size());
for (auto c : newVal)
{//若使用迭代器做参数,insert只能逐个字符插入
itr = s.insert(itr,c);
advance(itr, 1);
}
}
}
}*/
void replaceVal(string &s, const string oldVal, const string newVal)
{
string::size_type sLength = s.size(), oldLength = oldVal.size();
if (s[sLength - 1] != '.')s.push_back('.');
for (size_t index = 0; index != sLength; index++)
{//下标及replace方法
if (s.substr(index, oldLength)==oldVal)
{//replace接收一个起始下标值,一个长度范围,一个新串
s.replace(index, oldLength, newVal);
}
}
}
int main(int argc, char **argv) {
string str_a{"some people enjoy swimming, \nsome people wanna learn to swim,\nand some other people hate swimming"};
cout << str_a << endl;
string a, b;
cout << "旧的词: ";
cin >> a;
cout << "新的词: ";
cin >> b;
replaceVal(str_a,a,b);
cout << "更改后的句子"<<endl<<str_a << endl;
return 0;
}
给人名string加前/后缀
#include"stdafx.h"
#include<iostream>
#include<string>
using namespace std;
string NameAdd(string base, const string &front, const string &back)
{
base.insert(base.size(),back);
base.insert(0, front);
return base;
}
int main(int argc, char **argv) {
string Namebase,Addfront,Addback;
cout << "名字主体: ";
cin >> Namebase;
cout << "要添加的前缀: ";
cin >> Addfront;
cout << "要添加的后缀: ";
cin >> Addback;
string NewName = NameAdd(Namebase, Addfront, Addback);
cout << "旧名字: " << Namebase << endl;
cout <<"新名字: "<< NewName << endl;
return 0;
}