如题所述
#include <stdio.h>
#define MAX_CHAR 200
int read_line(char str[],int n);
int count_spaces(const char s[]);
void f1(char *s);
int main()
{
char str[MAX_CHAR+1];
printf("请输入字符串:");
read_line(str,MAX_CHAR);
f1(str);
printf("%d",count_spaces(str) +1); //单词的数量等于有效空格的数量加1
system("pause");
}
//读入字符串
int read_line(char str[],int n)
{
int ch,i=0;
while((ch=getchar())!='\n')
if(i<n)
str[i++]=ch;
str[i]='\0';
return i;
}
//计算字符串中空格的数量,只有空格后面跟字母的空格才计数。
int count_spaces(const char s[])
{
int count=0,i;
for(i=0;s[i]!='\0';i++)
if(s[i]==' ' && ((s[i+1]>='a' && s[i+1] <'z') || (s[i+1]>='A' && s[i+1] <'Z')) )
count++;
return count;
}
//去除字符串的前导空格。
void f1(char *s)
{
char *t;
t=s;
while(*s==' ')
s++;
while(*t++=*s++);
}
#define MAX_CHAR 200
int read_line(char str[],int n);
int count_spaces(const char s[]);
void f1(char *s);
int main()
{
char str[MAX_CHAR+1];
printf("请输入字符串:");
read_line(str,MAX_CHAR);
f1(str);
printf("%d",count_spaces(str) +1); //单词的数量等于有效空格的数量加1
system("pause");
}
//读入字符串
int read_line(char str[],int n)
{
int ch,i=0;
while((ch=getchar())!='\n')
if(i<n)
str[i++]=ch;
str[i]='\0';
return i;
}
//计算字符串中空格的数量,只有空格后面跟字母的空格才计数。
int count_spaces(const char s[])
{
int count=0,i;
for(i=0;s[i]!='\0';i++)
if(s[i]==' ' && ((s[i+1]>='a' && s[i+1] <'z') || (s[i+1]>='A' && s[i+1] <'Z')) )
count++;
return count;
}
//去除字符串的前导空格。
void f1(char *s)
{
char *t;
t=s;
while(*s==' ')
s++;
while(*t++=*s++);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2012-05-07
#include "stdio.h"
main()
{
int i,sum=0,s=0;
char str[100];
printf("请输入一些字符,之间用空格隔开,然后按回车键:\n");
gets(str);
for(i=0;str[i];i++)
{
if(str[i]==' ')
{
if(s) sum++;
s=0;
}
else s=1;
}
printf("共有单词 : %d 个 \n",sum);
}
main()
{
int i,sum=0,s=0;
char str[100];
printf("请输入一些字符,之间用空格隔开,然后按回车键:\n");
gets(str);
for(i=0;str[i];i++)
{
if(str[i]==' ')
{
if(s) sum++;
s=0;
}
else s=1;
}
printf("共有单词 : %d 个 \n",sum);
}
第2个回答 2011-12-04
想一下自己学过的知识点,不要这样索取代码,否则你永远没有长进.
提示一下,把输入的字符存储到一个缓存中,比如数组,然后挨个分析每个字符的类型,同时定义几个计数器,就可以解决问题的.追问
提示一下,把输入的字符存储到一个缓存中,比如数组,然后挨个分析每个字符的类型,同时定义几个计数器,就可以解决问题的.追问
我们还没学数组了
追答连数组都没学,哪你学了啥,gets()库函数会使用不?
追问不会