这道题和之前做的一道题很像
模仿对象
这道题其实和1029 旧键盘 (20 分)有异曲同工之妙
liuchuo大神的代码值得借鉴:
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s1, s2, ans;
cin >> s1 >> s2;
for (int i = 0; i < s1.length(); i++)
if (s2.find(s1[i]) == string::npos && ans.find(toupper(s1[i])) == string::npos)
ans += toupper(s1[i]);
cout << ans;
return 0;
}
原因:
- 巧妙使用了string中的find(),代替更容易想到的遍历
- 用
find()==string::npos
代表没有
我的模仿
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
string s1,s2,ans;
cin>>s1>>s2;
bool dx=s1.find('+');//标记上档键是否失效
for(int i=0;i<s2.length() ;++i){
if(s1.find(toupper(s2[i]))==string::npos) {
if(isupper(s2[i])&&dx) continue;
ans+=s2[i];
}
}
if(ans=="") cout<<endl;
else cout<<ans;
return 0;
}
三个错误点:
- 因为存在空行,所以这里不能用直接用cin,碰到空行cin是跳过,而getline是字符串置空。
- 标记上档键是否失效并不能用
bool dx=s1.find('+');
而应该用find()==string::npos
- 这里说是没有则输出空行,最后几行画蛇添足了
if(ans=="") cout<<endl;
else cout<<ans;
更改后
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
string s1,s2,ans;
getline(cin,s1);
getline(cin,s2);
bool dx=(s1.find('+')==string::npos);//标记上档键是否失效
for(int i=0;i<s2.length() ;++i){
if(s1.find(toupper(s2[i]))==string::npos) {
if(isupper(s2[i])&&dx) continue;
ans+=s2[i];
}
}
if(ans=="") cout<<endl;
else cout<<ans;
return 0;
}
最后放上liuchuo萌神的代码
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string bad, should;
getline(cin, bad);
getline(cin, should);
for (int i = 0, length = should.length(); i < length; i++) {
if (bad.find(toupper(should[i])) != string::npos) continue;
if (isupper(should[i]) && bad.find('+') != string::npos) continue;
cout << should[i];
}
return 0;
}
千里之行始于足下,共勉!