0

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

这一切都在 Stephen Kochan 写的“Programming in C”中进行了解释,但是当涉及到函数中的“lookingForWord”和“++wordCount”时,我不明白它是如何工作的countWords

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

2 回答 2

5

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

因此,该函数会将所有内容计为一个单独的单词,该单词由一个alphabetic()错误的字符分隔(因此它将“don't”和“o'clock”分别计为两个单词)。

于 2012-03-12T23:08:10.627 回答
0
  1. 该算法首先初始化lookingForWord为真(因为我们总是开始寻找一个词)
  2. 然后它循环直到找到标记值'\0'
  3. 它检查charat 位置i是否是字母
  4. 如果是,我们发现了一个新词,我们增加wordCount并设置lookingForWord为 false
  5. 我们将继续循环而不增加任何wordCount因为alphabetic(string[i])是真的但是lookingForWord假的
  6. 当我们遇到一个非字母字符时,我们设置wordCount为 false 所以下一个循环如果alphabetic(string[i])是 true,我们将增加wordCount

我有点不确定的是为什么这段代码的作者会放在下面一行:

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

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

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

但结果保持不变。

于 2012-03-12T23:27:56.907 回答