这是您的代码的工作版本和测试程序。
#include <stdbool.h>
#include <stdio.h>
static int wc(const char *str)
{
int count = 0;
bool inword = false;
char c;
while ((c = *str++) != '\0')
{
if (c == ' ')
inword = false;
else
{
if (inword == false)
count++;
inword = true;
}
}
return count;
}
static void Number(const char *tests[], int num_tests)
{
for (int i = 0; i < num_tests; i++)
printf("%d: [%s]\n", wc(tests[i]), tests[i]);
}
int main(void)
{
const char *tests[] =
{
"",
" ",
" ",
"a",
"a b",
" a b ",
" ab cd ",
"The quick brown fox jumps over the lazy dog.",
" The quick brown fox jumps over the lazy dog. ",
};
enum { NUM_TESTS = sizeof(tests) / sizeof(tests[0]) };
Number(tests, NUM_TESTS);
return 0;
}
请注意,您的 Number() 函数做了两项工作——并且应该只做一项,将另一项委托给一个单独的函数。它既计算单个字符串中的单词并打印相关信息。我将单词计数委托给一个单独的函数wc(),这极大地简化了Number() 中的代码——几乎到了不需要该函数的地步。还要注意,我的Number() 版本被告知它正在处理的数组的条目数,而不是依赖于像4 这样的幻数。请注意,我的代码的输出允许您检查它的准确性。简单地打印输出编号并不能让您如此轻松地检查准确性;您必须查看代码以了解数字的含义。请注意,您的Number() 函数被定义为返回int,但实际上并没有这样做。这个版本被定义为不返回任何东西,它不会。
代码的输出是:
0: []
0: [ ]
0: [ ]
1: [a]
2: [a b]
2: [ a b ]
2: [ ab cd ]
9: [The quick brown fox jumps over the lazy dog.]
9: [ The quick brown fox jumps over the lazy dog. ]
显然,如果您愿意,您可以使用<ctype.h> 中的isblank() 或isspace() 宏(函数)来优化空间测试,或者以其他方式定义单词和非单词之间的边界。不过,基本概念在相当反常的空格和单词序列中是可靠的。
如果你真的想要一个 2D 字符数组,编写代码来处理它并不难,尽管必须减少“懒狗”字符串以干净地适应 char data[][20]。基本思想保持不变——wc() 函数没有改变。
#include <stdbool.h>
#include <stdio.h>
static int wc(const char *str)
{
int count = 0;
bool inword = false;
char c;
while ((c = *str++) != '\0')
{
if (c == ' ')
inword = false;
else
{
if (inword == false)
count++;
inword = true;
}
}
return count;
}
static void Number(const char tests[][20], int num_tests)
{
for (int i = 0; i < num_tests; i++)
printf("%d: [%s]\n", wc(tests[i]), tests[i]);
}
int main(void)
{
const char tests[][20] =
{
"",
" ",
" ",
"a",
"a b",
" a b ",
" ab cd ",
"The quick brown fox",
" jumps over ",
" the lazy dog ",
};
enum { NUM_TESTS = sizeof(tests) / sizeof(tests[0]) };
Number(tests, NUM_TESTS);
return 0;
}
输出:
0: []
0: [ ]
0: [ ]
1: [a]
2: [a b]
2: [ a b ]
2: [ ab cd ]
4: [The quick brown fox]
2: [ jumps over ]
3: [ the lazy dog ]
像" ab cd " 示例这样的测试(在开头、中间和结尾都有两个空格)通常非常适合推动边缘情况——在更多的上下文中,而不仅仅是单词计数。例如,许多 shell 脚本无法正确处理像该字符串这样的参数。