这个C函数如何计算字符串中的单词数?

时间:2012-03-12 23:05:05

标签: c words counting

我需要一些帮助来了解countWords函数在下面的程序中是如何工作的。

在Stephen Cochan撰写的“Programming in C”中对此进行了解释,但在countWords函数中找到“lookingForWord”和“++ wordCount”时,我没有得到它的工作方式!

#include <stdio.h>
#include <stdbool.h>

//function to determine if a character is alphabetic
bool alphabetic (const char c)
{
    if ( (c >= 'a' && c <= 'z') || ( c >= 'A' && c <= 'Z'))     
        return true;
    else
        return false;
}

// function to count the number of words in a string
int countWords ( const char string[])
{
    int i, wordCount = 0;
    bool lookingForWord = true, alphabetic ( const char c);

    for ( i = 0; string[i] != '\0'; ++i)
        if (alphabetic(string[i]) )
        {
            if ( lookingForWord )
            {
                ++wordCount;
                lookingForWord = false;
            }
        }
        else
            lookingForWord = true;

    return wordCount;
}

int main ( void)
{
    const char text1[] = {"Well, here goes."};
    const char text2[] = { "And here we go... again"};
    int countWords (const char string[]);

    printf( " %s - words = %i\n", text1, countWords (text1));
    printf( " %s - words = %i\n", text2, countWords (text2));

    return 0;
}

2 个答案:

答案 0 :(得分:5)

您的函数计算单词中的第一个字母字符,然后跳过剩余的字母(通过将lookingForWord设置为false),一旦它遇到非字母字符,它就会重置{{ 1}}为true,以便它将下一个字母作为一个新词来计算。

因此,该函数将所有内容计为一个单独的单词,该单词由lookingForWord为假的字符分隔(因此它将“不”和“时”统计为每个两个单词)。

答案 1 :(得分:0)

  1. 算法首先将lookingForWord初始化为true(因为我们总是开始寻找一个单词)
  2. 然后循环,直到找到sentinel值'\ 0'
  3. 检查位置char的{​​{1}}是否为字母
  4. 如果是,我们发现了一个新词,我们增加i并将wordCount设为false
  5. 我们将保持循环而不会增加lookingForWord,因为wordCount为真但alphabetic(string[i])为假
  6. 当我们遇到非字母字符时,我们将lookingForWord设置为false,以便wordCount为真的下一个循环,我们将增加alphabetic(string[i])
  7. 我有点不确定的是为什么这段代码的作者放在以下行:

    wordCount

    我使用以下代码编译代码:

    bool lookingForWord = true, alphabetic ( const char c);
    

    但结果保持不变。