例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;
}
效果如下: