先看例题:
1033 旧键盘打字 (20 分)
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字会是怎样?
输入格式:
输入在 2 行中分别给出坏掉的那些键、以及应该输入的文字。其中对应英文字母的坏键以大写给出;每段文字是不超过 105 个字符的串。可用的字符包括字母 [a
-z
, A
-Z
]、数字 0
-9
、以及下划线 _
(代表空格)、,
、.
、-
、+
(代表上档键)。题目保证第 2 行输入的文字串非空。
注意:如果上档键坏掉了,那么大写的英文字母无法被打出。
输出格式:
在一行中输出能够被打出的结果文字。如果没有一个字符能被打出,则输出空行。
输入样例:
7+IE.
7_This_is_a_test.
输出样例:
_hs_s_a_tst
解题代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str1, str2;
//cin不能读入空格,一般情况下用getline(cin,str)
getline(cin, str1);//将str1赋值给cin,即输入str1
getline(cin, str2);//将str2赋值给cin,即输入str2
for(int i = 0; i < str2.size(); i++)
{
if(str1.find(toupper(str2[i])) != string :: npos) continue;
//如果在str1中找到了str2[i]的大写,跳过这个字符不输出,continue跳过
if(isupper(str2[i]) && str1.find('+') != string :: npos) continue;
//str2[i]是大写,而且在str1中找到‘+’这个符号,上档键坏了,大写无法输出,continue跳过这个字母,
cout << str2[i];
//如果都没跳过,则输出str2[i]
}
return 0;
}
关于string : : npos的使用说明:
1.如果作为一个返回值(return value)表示没有找到匹配项,就像上文代码中的
if(str1.find(toupper(str2[i])) != string :: npos) continue;
//如果在str1中找到了str2[i]的大写,跳过这个字符不输出,continue跳过
篇外话,关于c++的万能头文件,#include<bits/stdc++.h>
一个头文件代替了一大堆其他的头文件
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>