题目描述:
写出一个程序,接受一个有字母和数字以及空格组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。不区分大小写。
输入描述:
输入一个有字母和数字以及空格组成的字符串,和一个字符。
输出描述:
输出输入字符串中含有该字符的个数。
输入例子:
ABCDEF
A
输出例子:
1
这里需要注意的是大小写算同一个字母,所以对于输入的字符要加减32
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin, s);
char c;
cin >> c;
int m = 0;
for (auto q:s){
if(c == q||c == q-32||c == q+32) //在ascii表中,大小写相差32
m++;
}
cout << m << endl;
return 0;
}
但这里有个问题….数字0和小写f以及大写F也是相差32的,所以最好把大小写和字母分开讨论,运用count函数能更简单的输出。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
char ch;
while (cin >> str >> ch)
{
if (ch >= 'a'&&ch<='z')
cout << (count(str.begin(), str.end(), ch) + count(str.begin(), str.end(), (char)(ch - 32))) << endl;
else if (ch>='A'&&ch <= 'Z')
cout << (count(str.begin(), str.end(), ch) + count(str.begin(), str.end(), (char)(ch + 32))) << endl;
else
cout << count(str.begin(), str.end(), ch) << endl;
}
return 0;
}
当然也可以把字母全转换为大写,或者小写字母来处理。比如:
for(auto &c : s) //如果c是小写,输出大写,否则原样输出
c = toupper(c); //c是个引用,因为赋值语句将改变c。
注:toupper是cctype头文件中的函数,这个头文件中有些函数经常被用到,在这里写出一些常用的函数。
函数名称 | 作用 |
---|---|
isalnum(c) | 当c是字母或数字是为真 |
isalpha(c) | 当c是字母时为真 |
isdigit(c) | 当c是数字时为真 |
islower(c) | 当c是小写字母时为真 |
isupper(c) | 当c是大写字母时为真 |
isspace(c) | 当c是空格是为真 |
isxdigit(c) | 当c是十六进制数字时为真 |
tolower(c) | 如果c是大写字母,输出对应的小写,否则原样输出 |
toupper(c) | 如果c是小写的,输出对应大写,否则原样输出 |
用最后两个函数时,c要加&