How to use recursion in C language to count the number of words

Here is an example code in C language that calculates the number of words using recursion.

#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;

}

In the above code, we have defined a recursive function called countWords to calculate the number of words. In each recursive call, we check if the current character is a space, line break, or tab character. If it is, we set isWord to 0. Otherwise, if isWord is 0, it means we have encountered a new word. We then set it to 1 and increase the word counter wordCount.

In the main function, we defined an example string str and then called the countWords function to calculate the number of words and print the result.

After running the code, the output will be: Number of words: 6 (based on the example string). Make sure to replace the example string with the actual string you want to count the number of words for when using it.

Below is an example code in C language using recursion to count the number of words.

#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;

}

In the above code, we have defined a recursive function countWords to count the number of words. In each recursive call, we check if the current character is a space, newline, or tab. If it is, we set isWord to 0. Otherwise, if isWord is 0, it means we have encountered a new word, so we set it to 1 and increase the word counter wordCount.

In the main function, we defined an example string str, then called the countWords function to calculate the number of words, and printed out the result.

By running the code, it will output the result as: Number of words: 6 (based on the example string). Make sure to replace the example string with the actual string you want to count the number of words for when using it.

bannerAds