C++中,如何知道一个STRING中字母与数字的数量?

如题所述

代码如下,循环遍历字符串,然后和asc码做比较,分别统计输出
#include <string>
#include<iostream>
using namespace std;

int main()
{
std::string tmpStr = "123jfkd";
int count_n = 0;
int count_c = 0;
for(unsigned long i = 0; i < tmpStr.length(); ++i)
{
if(tmpStr[i] <= 'z' && tmpStr[i] >= 'a')
{
count_c++;
}
else if(tmpStr[i] <= 'Z' && tmpStr[i] >= 'A')
{
count_c++;
}
else if(tmpStr[i] <= '9' && tmpStr[i] >= '0')
{
count_n++;
}
}
std::cout << "number of 字母 is: " << count_c << " number of 数字 is: " << count_n << std::endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-04-01
遍历一遍字符串.然后统计出字母和数字的数量就可以了.
这个只要订好字母,数字的规则.实现很简单的.
第2个回答  2011-04-01
这个要用判定去统计吧。字母和数字的ascii玛是可以用int型去比较的
相似回答