怎么用C语言递归求单词个数

   2025-02-05 9720
核心提示:下面是用C语言递归来求单词个数的示例代码:#includestdio.h//定义递归函数来计算单词个数intcountWords(charstr[]){staticintwo

下面是用C语言递归来求单词个数的示例代码:

#include <stdio.h>

// 定义递归函数来计算单词个数

int countWords(char str[]) {

    static int wordCount = 0;

    static int isWord = 0;

    if (str[0] == '\0') {

        return wordCount;

    }

    if (str[0] == ' || str[0] == '\n' || str[0] == '\t') {

        isWord = 0;

    } else if (isWord == 0) {

        isWord = 1;

        wordCount++;

    }

    countWords(str + 1); // 递归调用,移动到下一个字符

    return wordCount;

}

int main() {

    char str[] = "Hello World, this is a sentence.";

    // 调用递归函数计算单词个数

    int numWords = countWords(str);

    printf("单词个数:%d\n", numWords);

    return 0;

}

上述代码中,我们定义了一个递归函数countWords来计算单词个数。在每一次递归调用中,我们判断当前字符是否为空格、换行符或制表符,如果是,则将isWord标记为0;否则,如果isWord为0,表示遇到了新的单词,我们将其标记为1,并增加单词计数器wordCount。

在主函数中,我们定义了一个示例字符串str,然后调用countWords函数来计算单词个数,并将结果打印出来。

运行该代码,将输出结果为:单词个数:6(根据示例字符串)。请确保在实际使用时将示例字符串替换为你要统计单词个数的实际字符串。

下面是用C语言递归来求单词个数的示例代码:

#include <stdio.h>

// 定义递归函数来计算单词个数

int countWords(char str[]) {

    static int wordCount = 0;

    static int isWord = 0;

    if (str[0] == '\0') {

        return wordCount;

    }

    if (str[0] == ' || str[0] == '\n' || str[0] == '\t') {

        isWord = 0;

    } else if (isWord == 0) {

        isWord = 1;

        wordCount++;

    }

    countWords(str + 1); // 递归调用,移动到下一个字符

    return wordCount;

}

int main() {

    char str[] = "Hello World, this is a sentence.";

    // 调用递归函数计算单词个数

    int numWords = countWords(str);

    printf("单词个数:%d\n", numWords);

    return 0;

}

上述代码中,我们定义了一个递归函数countWords来计算单词个数。在每一次递归调用中,我们判断当前字符是否为空格、换行符或制表符,如果是,则将isWord标记为0;否则,如果isWord为0,表示遇到了新的单词,我们将其标记为1,并增加单词计数器wordCount。

在主函数中,我们定义了一个示例字符串str,然后调用countWords函数来计算单词个数,并将结果打印出来。

运行该代码,将输出结果为:单词个数:6(根据示例字符串)。请确保在实际使用时将示例字符串替换为你要统计单词个数的实际字符串。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言