C++中,如何知道一个STRING中字母与数字的数量?
3个回答
展开全部
代码如下,循环遍历字符串,然后和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;
}
#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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询