用C++统计字符串中的数字、字符和特殊字符的个数

243 篇文章 8 订阅

    例2:用C++程序,统计一个字符串中的数字、字符和特殊字符的个数

代码如下:

//分别统计一个字符串中的数字、字母和特殊字符的个数
#include<iostream>
#include <string>
using namespace std;

//统计函数
bool cal_num(string str, int count[])
{
	bool bRet = false;
	if (str.length() <= 0) {
		return bRet;
	}

	char *pstr = NULL;
	pstr = &str[0];
	while (*pstr != 0)
	{
		if (*pstr >= '0' && *pstr <= '9') //统计数字个数
		{
			count[0]++;
		}
		else if ((*pstr >= 'a' && *pstr <= 'z') || (*pstr >= 'A' && *pstr <= 'Z'))
		{ //统计字母个数
			count[1]++;
		}
		else if (*pstr == ' ')
		{ //统计空格个数
			count[2]++;
		}
		else
		{ //统计其他字符个数
			count[3]++;
		}
		pstr++; //移动字符指针
	}

	return true;
}

int main()
{
	string inputStr;
	int i, count[4]; 
	//count[0]表示数字个数,
	//count[1]表示字母个数
	//count[2]表示空格个数
	//count[3]表示其他字符个数 ,default
	memset(count, 0, 4 * sizeof(int)); //将数组count[]里的元素全部置0

	cout << "请输入一条字符串: " << endl;
	getline(cin, inputStr);
	bool bRet = cal_num(inputStr, count);
	if (!bRet) {
		cout << "字符串为空" << endl;
		return -1;
	}

	cout << "\r\n 统计结果如下: " << endl;
	for (i = 0; i < 4; i++)
	{
		switch (i)
		{
		case 0:
			cout << " 1) 数字个数: " << count[i] << endl;
			break;
		case 1:
			cout << " 2) 字母个数:" << count[i] << endl;
			break;
		case 2:
			cout << " 3) 空格个数:" << count[i] << endl;
			break;
		default:
			cout << " 4) 其他字符个数:" << count[i] << endl;
			break;
		}
	}

	return 0;
}


效果如下:

 

  • 14
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值