1 // 2 // main.c 3 统计输入单词数 4 5 Created by LongMa on 2019/6/27. 6 Copyright © 2019 . All rights reserved. 7 // 8 9 #include <stdio.h> 10 #include <string.h> 11 12 int main(int argc,const char * argv[]) { 13 14 输入一个英文句子,英文句以空格分隔。统计句子中有多少个单词。 15 eg:how are you,有3个单词 16 char string[80]; 17 printf("请输入英文句子:"); 18 gets(string19 20 char c; 21 char kongGe[2] = " ; 22 int word = 023 int num = 24 25 for (int i = 0; (c = string[i]) != '\0'; i++) { 26 if (c == 32) {当前位为空格(ASCII码值为32)时,word记录为0.注意:xcode中strcmp(&c," ")为-120,不为0,strcmp比较的是字符串,不能比较字符和字符串! 27 printf(%d,%d是否相等:%d\n",c,kongGe[0],strcmp(&kongGe[c)); 28 word = 29 }else{当前位不为空格时 30 if(0 == word){上一位为空格/第一位是字母时 31 num += 132 word = 33 }上一位不为空格时,不能算一个单词 34 do nothing 35 } 36 } 37 } 38 39 printf(语句:%s\n40 printf(单词数:%d个,num); 41 return 42 }
log:
请输入英文句子:warning: this program uses gets(),which is unsafe.
how are you
32,32是否相等:-120
32,32是否相等:-120
语句:how are you
单词数:3个Program ended with exit code: 0