我需要编写一个函数来计算字符串中的单词.出于此赋值的目的,"单词"被定义为非空的非空白字符序列,通过空格与其他单词分隔.
这是我到目前为止:
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;
Run Code Online (Sandbox Code Playgroud)
我不确定它是否有效,因为我无法测试它直到我的整个程序完成并且我不确定它是否会起作用,是否有更好的方法来编写这个函数?
你需要
int words(const char sentence[])
{
}
Run Code Online (Sandbox Code Playgroud)
(注意大括号).
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"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60171 次 |
| 最近记录: |