华为机试题:计算字符个数

题目描述:
写出一个程序,接受一个有字母和数字以及空格组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。不区分大小写。
输入描述:

输入一个有字母和数字以及空格组成的字符串,和一个字符。

输出描述:

输出输入字符串中含有该字符的个数。

输入例子:

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要加&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值