我需要编写一个函数来计算字符串中的单词数。为了 这个任务的目的,一个“词”被定义为一个序列 非空,非空白字符,与其他单词分开 空格。
这是我目前所拥有的:
int words(const char sentence[ ]);
int i, length=0, count=0, last=0;
length= strlen(sentence);
for (i=0, i<length, i++)
if (sentence[i] != ' ')
if (last=0)
count++;
else
last=1;
else
last=0;
return count;
我不确定它是否有效,因为在我的整个程序完成之前我无法测试它,而且我不确定它是否有效,有没有更好的方法来编写这个函数?
最佳答案
你需要
int words(const char sentence[])
{
}
(注意大括号)。
For 循环使用 ;
而不是 ,
。
在没有任何免责声明的情况下,我会这样写:
#include <string.h>
#include <stdio.h>
int words(const char sentence[ ])
{
int counted = 0; // result
// state:
const char* it = sentence;
int inword = 0;
do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r': // TODO others?
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);
return counted;
}
int main(int argc, const char *argv[])
{
printf("%d\n", words(""));
printf("%d\n", words("\t"));
printf("%d\n", words(" a castle "));
printf("%d\n", words("my world is a castle"));
}
关于计算字符串中的单词 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12698836/