• C语言错误:计算字符串中特定单词的出现次数


    问题描述:

    这个函数的问题是它会处理所有的子字符串,而不是像这样的词,例如,如果我在“hifive toeveryone”中寻找“hi”,它会返回 1

    1. int HowManyString(char *satz,char *word) {
    2. int coun = 0;
    3. while (strlen(word)<strlen(satz)) {
    4. if (strstr(satz,word)==NULL) {
    5. return coun;
    6. } else {
    7. satz=strstr(satz,word)+strlen(word);
    8. if(*(satz)==' '||*(satz)=='\0'){
    9. coun++;
    10. } else {
    11. return coun;
    12. }
    13. }
    14. }
    15. return coun;
    16. }

    解决思路一:

    这是一个实现您正在寻找的功能:

    1. int count_words(const char *sentence, const char *word)
    2. {
    3. int counter = 0;
    4. for (const char *p = sentence; *p; ++p) {
    5. // Skip whitespaces
    6. if (isspace(*p))
    7. continue;
    8. // Attempt to find a match
    9. const char *wp = word, *sp = p;
    10. while (*wp != '\0' && *sp != '\0' && *wp == *sp) {
    11. ++wp;
    12. ++sp;
    13. }
    14. // Match found AND a space after AND a space before
    15. if (*wp == '\0' && (isspace(*sp) || *sp == '\0') && (p == sentence || isspace(*(p-1)))) {
    16. ++counter;
    17. p = sp - 1;
    18. }
    19. // End of sentence reached: no need to continue.
    20. if (*sp == '\0')
    21. return counter;
    22. }
    23. return counter;
    24. }

    用法:

    1. int main(void)
    2. {
    3. const char sentence[] = "I is Craig whoz not me, not him, not you!";
    4. const char word[] = "not";
    5. int occ = count_words(sentence, word);
    6. printf("There are %d occurences.\n", occ);
    7. }

    输出:

    There are 3 occurences.

    解决思路二(这是解决小编问题的思路):

            以上仅为部分解决思路介绍,请查看全部内容,请添加下方公众号后回复001,即可查看。公众号有许多评分最高的编程书籍和其它实用工具,绝对好用,可以放心使用

            如果您觉得有帮助,可以关注公众号——定期发布有用的资讯和资源​

            

  • 相关阅读:
    Las Vegas 与回溯组合法解八皇后问题
    FreeRTOS 软件定时器的使用
    C. Mr. Perfectly Fine
    Android系统编译优化:使用Ninja加快编译
    你好,我是测试划水老师傅!
    【分布式深度学习 二】--- 分布式训练demo
    MybatisPlus通用枚举
    基于Linux安装TCL
    新人一看就懂:Dubbo3 + Nacos的RPC远程调用框架demo
    java毕业生设计校园绿化管理系统计算机源码+系统+mysql+调试部署+lw
  • 原文地址:https://blog.csdn.net/qq_38334677/article/details/126107213