我需要一些帮助来了解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;
}
答案 0 :(得分:5)
您的函数计算单词中的第一个字母字符,然后跳过剩余的字母(通过将lookingForWord
设置为false
),一旦它遇到非字母字符,它就会重置{{ 1}}为true,以便它将下一个字母作为一个新词来计算。
因此,该函数将所有内容计为一个单独的单词,该单词由lookingForWord
为假的字符分隔(因此它将“不”和“时”统计为每个两个单词)。
答案 1 :(得分:0)
lookingForWord
初始化为true(因为我们总是开始寻找一个单词)char
的{{1}}是否为字母i
并将wordCount
设为false lookingForWord
,因为wordCount
为真但alphabetic(string[i])
为假lookingForWord
设置为false,以便wordCount
为真的下一个循环,我们将增加alphabetic(string[i])
我有点不确定的是为什么这段代码的作者放在以下行:
wordCount
我使用以下代码编译代码:
bool lookingForWord = true, alphabetic ( const char c);
但结果保持不变。