下面是您的代码的工作版本和测试程序。
#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;
}
请注意,您函数完成两项工作 - 并且应该只做一,委托对方一个单独的函数。它既计算单个字符串中的单词并打印相关信息。我将计数单词委托给单独的函数wc()
,这极大地简化了中的代码 - 几乎不需要该函数。还请注意,我的版本被告知它正在处理的数组的条目数量,而不是依赖像4
这样的幻数。请注意,我的代码输出允许您检查它的准确性。只需打印输出号码不会让您轻松检查准确性;您必须查看代码才能了解数字的含义。请注意,您的函数被定义为返回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. ]
很显然,你可以使用isblank()
或isspace()
宏(功能)从<ctype.h>
细化空间测试,如果你愿意,也可以定义字和不可─之间的边界用其他方式说话。尽管如此,基本的概念是可靠的,可以跨越空白和文字的相当不正确的序列。
如果你真的想要一个二维数组的字符,编写代码来处理这个问题并不难,尽管'懒狗'字符串将不得不简化为适合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脚本不会正确处理像那个字符串这样的参数。
如果字符串是 “空”,即,仅包括' “\ 0”''然后\ 0'将被计数,但否则'do .. while()'循环条件将'\ 0'排除在考虑之外。我建议使用'while(){...}'循环。想一想“何时出现'\ 0'字符”。它不是* C字符串中的字符*,而是它的结束标记。 –
当它到达\ 0字符时,循环停止,那么为什么你认为它会被计算? – immibis
while循环不起作用。如果我没有在一行中放入任何二维数组,那么这一段时间根本不会被执行......尽管在我写论坛之前,我仍尝试过。 –