C语言:编写一个函数,统计一个字符串中it单词的个数,求大神

如题所述

   #include <stdio.h>
   #include <string.h>
   #include <ctype.h>
   
   int count_word(const char * sentense, const char * word, int caseless)
   {
           int number = 0;
           const char * p, * current = sentense;
           int head, tail;
           int len = strlen(sentense);
           //printf("len:%d\n", len);
           while (1) {
                   //printf("c: %s\n", current);
                   if (caseless)
                           p = strcasestr(current, word);
                   else
                           p = strstr(current, word);
                   if (p == NULL)
                           break;
                   // check if it's a word
                   head = p - sentense;
                   tail = head + strlen(word);
   
                   //printf("p: %s\n", p);
                   //printf("head: %d\n", head);
                   //printf("tail: %d\n", tail);
                   if ( (head == 0 || !isalpha(sentense[head-1])) &&
                                   (tail == len || !isalpha(sentense[tail]))) {
                           number++;
                           //printf("      num++\n");
                   }
                   current = p + strlen(word);
           }
           return number;
   }
   
   int main()
   {
           int n = count_word("It's a nice day today, isn't it? . leave it alone! got it", "it", 1);
           printf("%d\n", n);
           return 0;
   }

温馨提示:答案为网友推荐,仅供参考
相似回答