华为题库-计算字符个数

题目:

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

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

输出描述:

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

示例1
输入
复制

ABCDEF
A

输出
复制

1

思路:

通过getline(cin,str)及cin>>ch来输入题目所需要的字符串和字符,遍历字符串,通过str[i[ch来判断是否字符串中有输入的字符,有的话对其进行计数。但是,由于不区分大小写,大小写字母的ASIIC码之间相差32,a-z:97-122,A-Z:65-90,所以通过对其进行加减32来判断str[i]-32ch str[i]+32==ch,并对其进行计数。

或者全部转换成大写字母或者小写字母再进行判断。

if(ch>='a' && ch<='z')
        ch -= 32;//将ch转换为大写
    for(int i =0; i<str.length(); ++i)
    {
        if(str[i]>='a' && str[i]<='z')
            str[i] -= 32; //将str[i]转化为大写
        if(str[i] == ch)
            ++count;
    }

代码:

#include <iostream>
#include <string>
using namespace std;

int CalculateNumber()
{
	string str;
	char ch;
	getline(cin, str);
	cin >> ch;
	int count = 0;

	for (int i = str.length() - 1; i >= 0 ; i--)
	{
		if (str[i] == ch)
		{
			count++;
		}
		else if (str[i] - 32 == ch )
		{
			count++;
		}
		else if (str[i] + 32 == ch)
		{
			count++;
		}
	}

	return count;
}

int main()
{
	int result = CalculateNumber();
	cout << result << endl;

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值