将一段字符串中的could you 和can you 改成 I can 和 I could
运用到了replace()与substr();这也是string类中的重点,当然重点的还有find(),本题没用到,因为find()只能找一个字符;
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="can you and could you";
for(int i=0;i<s.size()-9;i++){
string ss1=s.substr(i,i+7);
string ss2=s.substr(i,i+9);
if(ss1=="can you"){
s.replace(i,7,"I can");
}
if(ss2=="could you"){
s.replace(i,9,"I could");
}
}
cout << s;
return 0;
}
本文介绍了如何使用C++中的`replace()`和`substr()`函数来替换字符串中的特定子串。通过示例代码展示了将字符串canyouandcouldyou中的canyou和couldyou替换为Ican和Icould的过程。最终输出结果为IcanandIcould。

705

被折叠的 条评论
为什么被折叠?



