字符串str,、数字、空格以及其他字符出现的次数
指针
#include
#include
/*统计函数*/
void check(char *str)
{
int i,number=0,space=0,zimu=0,other=0;
char *p=str;
for(i=0;i='0' && *(p+i)<='9') /*数字*/
number++;
else if(*(p+i) == 32) /*空格*/
space++;
else if((*(p+i)>='a' && *(p+i)<='z')||(*(p+i)>='A' && *(p+i)<='Z'))
zimu++;/*其它字符*/
else other++;
}
printf("%s\n",str);
printf("number:%d\nspace:%d\nzimu:%d\nother
char:%d\n",number,space,zimu,other); }
/*主函数*/
main()
{
char string[100];
gets(string); /*输入字符串,因为要包括空格,不能用scanf()*/
check(string); /*调用函数*/
}
引用
#include
#include
using namespace std;
inline int str_len(char *p) {
{
if(p==NULL)
return 0;
int n=0; char *q=p;
while(*q!='\0')
{
n++; q++;
}
return n;
}
}
void tongji(char *st,int n,int &zimu,int &shuzi,int &kongge,int &other)
{
char str;
for(int i=0;i='A'||str<='z'&&str>='a')
zimu+=1;
else if(str<='9'&&str>='0')
shuzi+=1;
else if(str==' ')
kongge+=1;
else
other+=1;
}
}
int main(int argc, char *argv[])
{
char s[1000];
int zimu=0,shuzi=0,kongge=0,other=0,n;
cout<<"请输入一个字符串:";
cin>>s;
n=str_len(s);
tongji(s,n,zimu,shuzi,kongge,other);
cout<<"统计结果如下:"<