活学活用,怎么高兴怎么来(通过就行)
高级方法还得自己去摸索
把一个字符串中特定的字符全部用给定的字符替换,得到一个新的字符串。
输入格式
只有一行,由一个字符串和两个字符组成,中间用单个空格隔开。
字符串是待替换的字符串,字符串长度小于等于 3030 个字符,且不含空格等空白符;
接下来一个字符为需要被替换的特定字符;
接下来一个字符为用于替换的给定字符。
输出格式
一行,即替换后的字符串。
输出时每行末尾的多余空格,不影响答案正确性
样例输入
hello-how-are-you o O
样例输出
hellO-hOw-are-yOu
我不会写函数,我只是函数的搬运工
the first method
#include<bits/stdc++.h>
using namespace std;
int main(){
string a;
char x,n;
cin>>a>>n>>x;
int len=a.length();//string函数库,length();size();获取字符串长度
for(int i=0;i<len;i++){
if(a[i]==n)
a.at(i)=x;//at();输出或修改某个字符
}
cout<<a;
return 0;
}
The second method
#include<iostream>
#include<string>
using namespace std;
int main(){
string s1;
string a,b;
int i;
cin>>s1>>a>>b;
i=s1.find(a);
// cout<<i;//find()函数用于查找数组中的某一个指定元素的位置。
while(i!=-1){
s1.replace(i,a.length(),b);//替换字符串函数,用b替换指定字符串从起始位置i开始长度为a.length()的字符
i=s1.find(a);//更新下一个元素出现位置
}
cout<<s1;
return 0;
}
The third method
这个清晰简单
#include<bits/stdc++.h>
using namespace std;
int main(){
char a[33];
char x,n;
cin>>a>>n>>x;
int len=strlen(a);//获取字符串长度
for(int i=0;i<len;i++){//一一进行比较替换
if(a[i]==n)
a[i]=x;
}
cout<<a;
return 0;
}