1、提示并输入一个字符串,统计该字符串中字母个数、数字个数、空格个数、其他字符的个数
only只是一个简单的小练习
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str; //定义一个字符串类型
cout<<"请输入一个字符串:";
getline(cin,str); //使用getline函数能够输入含有空格的字符串
int len = str.length();
//分别用来统计字符串中:字母,数字,空格,其他字符的个数,如果有就加1
int letters = 0,digits = 0,spaces = 0,others = 0;
for(int i = 0;i < len;i++)
{
char ch = str[i]; //定义一个字符类型接收str字符串里的每一个字符,进行判断
//判断是否为字母
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
letters++;
}
//判断是否为数字
else if(ch >= '0' && ch <= '9')
{
digits++;
}
//判断是否为空格
else if(ch == ' ')
{
spaces++;
}
//如果以上都不是,那就说明是别的字符
else
{
others++;
}
}
//输出统计出的结果
cout<<"该字符串中字母有:"<<letters<<"个"<<endl;
cout<<"该字符串中数字有:"<<digits<<"个"<<endl;
cout<<"该字符串中空格有:"<<spaces<<"个"<<endl;
cout<<"该字符串中其它字符有:"<<others<<"个"<<endl;
}
输出结果如下:
补充:
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
string str;
int alpha = 0;
int digit = 0;
int space = 0;
int other = 0;
cout<<"请输入一个字符串:";
getline(cin, str);
for(unsigned int i = 0; i < str.size(); i++)
{
if( isalpha(str.at(i)) )
{
alpha++;
}else if( isdigit(str[i]) )
{
digit++;
}else if(isspace(str.at(i)))
{
space++;
}else
{
other++;
}
}
cout<<"alpha = "<<alpha<<" digit = "<<digit<<" space = "<<space<<" other = "<<other<<endl;
return 0;
}