1029 旧键盘 (20 分)+几个常用函数
题目
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及实际被输入的文字,请你列出肯定坏掉的那些键。
输入格式:
输入在 2 行中分别给出应该输入的文字、以及实际被输入的文字。每段文字是不超过 80 个字符的串,由字母 A-Z(包括大、小写)、数字 0-9、以及下划线 _(代表空格)组成。题目保证 2 个字符串均非空。
输出格式:
按照发现顺序,在一行中输出坏掉的键。其中英文字母只输出大写,每个坏键只输出一次。题目保证至少有 1 个坏键。
输入样例:
7_This_is_a_test
_hs_s_a_es
输出样例:
7TI
代码
参考自柳神
#include<iostream>
#include<string>
#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函数的返回值是无符号整型,如果查找不到,就会返回4294967295(string::npos表示-1或4294967295)一般常用string::npos
参考 博客园 同勉共进
/*测试string中的find*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
//测试size_type find (charT c, size_type pos = 0) const noexcept;
string st1("babbabab");
cout << st1.find('a') << endl;//1 由原型知,若省略第2个参数,则默认从位置0(即第1个字符)起开始查找
cout << st1.find('a', 0) << endl;//1
cout << st1.find('a', 1) << endl;//1
cout << st1.find('a', 2) << endl;//4 在st1中,从位置2(b,包括位置2)开始,查找字符a,返回首次匹配的位置,若匹配失败,返回npos
cout << st1.rfind('a',7) << endl;//6 关于rfind,后面讲述
cout << st1.find('c', 0) << endl;//4294967295
cout << (st1.find('c', 0) == -1) << endl;//1 string:npos
cout << (st1.find('c', 0) == 4294967295) << endl;//1 两句均输出1,原因是计算机中-1和4294967295都表示为32个1(二进制)
cout << st1.find('a', 100) << endl;//4294967295 当查找的起始位置超出字符串长度时,按查找失败处理,返回npos
//测试size_type find (const basic_string& str, size_type pos = 0) const noexcept;
string st2("aabcbcabcbabcc");
string str1("abc");
cout << st2.find(str1, 2) << endl;//6 从st2的位置2(b)开始匹配,返回第一次成功匹配时匹配的串(abc)的首字符在st2中的位置,失败返回npos
//测试size_type find (const charT* s, size_type pos = 0) const;
cout << st2.find("abc", 2) << endl; //6 同上,只不过参数不是string而是char*
//测试size_type find (const charT* s, size_type pos, size_type n) const;
cout << st2.find("abcdefg", 2, 3) << endl;//6 取abcdefg得前3个字符(abc)参与匹配,相当于st2.find("abc", 2)
cout << st2.find("abcbc", 0, 5) << endl;//1 相当于st2.find("abcbc", 0)
cout << st2.find("abcbc", 0, 6) << endl;//4294967295 第3个参数超出第1个参数的长度时,返回npos
return 0;
}
- 原c中< ctype >中的toupper()
功能:将小写字母转化为大写字母,如果是其他字符,则不进行转化。
函数声明:int toupper(int c)
c是需要转化的字符,因为字符型和整形是可以相互转化的,所以括号里面为整型,返回的也是整型,但是输出的是转化后的字符
#include<iostream>
#include<cstdio>
#include<ctype.h>
#include<string>
using namespace std;
int main()
{
string str1;
cin >> str1;
int l1 = str1.length();
for (int i = 0; i < l1; i++)
{
printf("%c", toupper(str1[i]));
}
return 0;
}