C语言编程题:从键盘输入一串字符,统计其中的数字与字母个数并输出。(用指针实现)

如题所述

#include <stdio.h>
int main()
{
int n, t, n1=0, n2=0;
char str[1001], *p;

printf("请输入一个字符串: ");
gets(str);
p = str;
while (*p!='\0') {
if(*p>='0' && *p<='9') n1 ++;
else if (*p>='a' && *p<='z' || *p>='A' && *p<='Z') n2 ++;
p ++;
}
printf("其中数字有%d个, 字母有%d个\n",n1, n2);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-24
#include<stdio.h>
#include<string.h>

void main()
{
char ch[128];
int alpha = 0, num = 0, spc = 0, oth = 0;
int i = 0;

printf("请输入字符串: ");
while ((ch[i++] = getchar()) != '\n');

for (i = 0; i < strlen(ch); i++)
{
if ((ch[i] >= 'a' && ch[i] <= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z'))
alpha++;
else if (ch[i] >= '0' && ch[i] <= '9') num++;
else if (ch[i] == 32) spc++;
else oth++;
}
printf("字母: %d, 数字: %d, 空格: %d, 其他: %d\n", alpha, num, spc, oth);
}
第2个回答  2011-12-28
#include<stdio.h>
int main()
{
char c;
int word=0,number=0,gap=0,other=0;
while((c=getchar())!='\n')
{
if(c>='A'&&c<='Z'||c>='a'&&c<='z')
word++;
else if(c>='0'&&c<='9')
number++;
else if(c==' ')
gap++;
else
other++;
}
printf("word:%d\tnumber:%d\tgap:%d\tother:%d\n",word,number,gap,other);
return 0;
}
第3个回答  2011-12-24
#include <stdio.h>
#define N 200
void count(char *);
int main()
{
char *ch,chr;
ch=malloc(N+1);
printf("请输入输入一行字符:\n");
gets(ch);
count(ch);
getchar();
}

void count(char *ch)
{
char *temp=ch;
int i, chr=0,digit=0;
while(*ch != '\0')
{
if((*ch>='A' && *ch<='Z') ||(*ch>='a' && *ch<='z') )
chr++;
else if (*ch>='0' && *ch<='9')
{digit++;}
ch++;
}
printf("该字符串字母有%d个,数字有:%d个\n",chr,digit);
}本回答被提问者和网友采纳