1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<ctype.h> 4 5 int word_cnt(char *str); 6 void word_print(char *str, int beg, int end); 7 //提取单词 8 void word_split(char *str); 9 10 int main() 11 { 12 char str[128]; 13 //int cnt = 0; 14 gets_s(str,128); 15 //cnt = word_cnt(str); 16 //printf("count = %d\n",cnt); 17 word_split(str); 18 system("pause"); 19 return 0; 20 } 21 22 int word_cnt(char *str) 23 { 24 int cnt = 0; 25 int i = 0; 26 while(str[i] != '\0') 27 { 28 //根据单词末尾判断 29 if(isalnum(str[i]) && (str[i+1] == ' ' || str[i+1] == '\0')) 30 ++cnt; 31 //根据单词开头判断 32 //if(isalnum(str[i]) && (i == 0 || i != 0 && str[i-1] == ' ')) 33 ++i; 34 } 35 return cnt; 36 } 37 38 void word_print(char *str, int beg, int end) 39 { 40 while(beg <= end) 41 { 42 putchar(str[beg]); 43 beg++; 44 } 45 printf("\n"); 46 } 47 48 void word_split(char *str) 49 { 50 int cnt = 0;//记录单词的个数 51 int i = 0;//下标 52 int word_beg, word_end;//一个单词的开始、终止下标 53 54 while(str[i] != '\0') 55 { 56 //找到单词的开头 57 while(str[i] && !(isalnum(str[i]) && (i== 0 || i != 0 && str[i-1] == ' '))) 58 ++i; 59 if(str[i] == '\0') 60 break; 61 word_beg = i; 62 63 ++cnt; 64 //找到单词的结尾 65 while(!(isalnum(str[i]) && (str[i+1] == '\0' || str[i+1] == ' '))) 66 ++i; 67 word_end = i; 68 ++i; 69 printf("%dth: ",cnt); 70 word_print(str,word_beg,word_end); 71 } 72 }