c语言统计一个字符串中单词的个数.docVIP

  • 116
  • 0
  • 约 6页
  • 2017-06-07 发布于重庆
  • 举报
c语言统计一个字符串中单词的个数

c语言 统计一个字符串中单词的个数这个程序可以自动清除多余的空格。 #include stdio.h int count_word(char *str); void main() { char str1[80]; int sum=0; puts(\n please enter a string); gets(str1); sum=count_word(str1); printf(there are %d words in this sentence,sum); } int count_word(char *str) { int count,flag; char *p; count=0; flag=0; p=str; while(*p!=\0)/*当字符串没有到结尾的时候,重头到尾的循环*/ { if(*p== )/*假如字符串遇到空格,就将flag清零,同时可以过滤掉多余的空格*/ flag=0; else if(flag==0)/*当字符串不是空格时,假如flag为0,那么计算器加1,既是遇到空格后的第一个字符时*/ { flag=1;/*将flag标记回1,这样在遇到第一个字符后的字符时可以将他过滤掉,直到遇到空格时,在清零*/ count++; } p++; } return count; } C语言编程题求教----输入一个字符 统计其中的单词个数 输入一串字符 统计其中的单词个数。*/各个单词间用空格隔开 空格数可以是多个/* 例子: Input:Lets go to room 209 count=5 这是我做的程序: #include stdio.h int main(void) { char ch; int c,m; printf(Input words:); c=1; while((ch=getchar())!=\n){ if(ch== ) c++; } printf(count=%d\n,c); return 0; } 但是如果是多个空格就要多统计出单词个数来。。。请教要怎样才能使多个空格只算作一个呢??设置一个标志word,表示单词是否开始。如果一直是空格的话,word=0,一旦看到不是空格,并且word是0,则意味着一个新单词开始,将个数增1并将word置为1。 #include stdio.h main() { char c; int i,num=0,word=0; while((c=getchar())!=\n) if(c== ) word=0; else if(word==0) { word=1; num++; } printf(There are %d words in the line\n,num); } 逆序重新存放 #includestdio.h main() { int a[5], i, temp; /*定义数组及变量为基本整型*/ printf(please input array a:\n); for (i = 0; i 5; i++) /*逐个输入数组元素*/ scanf(%d, a[i]); printf(array a:\n); for (i = 0; i 5; i++) /*将数组中的元素逐个输出*/ printf(%d , a[i]); printf(\n); for (i = 0; i 2; i++) /*将数组中元素的前后位置互换*/ { temp = a[i]; /*元素位置互换的过程借助中间变量temp*/ a[i] = a[4-i]; a[4-i] = temp; } printf(Now array a:\n); for (i = 0; i 5; i++) /*将转换后的数组再次输出*/ printf(%d , a[i]);} 赞同#includestdio.h void main() { int a[10],i,j,temp; for(i=0;i10;i++) scanf(%d,a[i]); for(i=0;i5;i++) for(j=9-i;1;j++) { temp=a[j]; a[j]=a[i]; a[i]=temp;break; } for(i=0;i10;i++) printf( %d,a[i]); } //3. 将一个数组

文档评论(0)

1亿VIP精品文档

相关文档