计算字符串中的单词 - C 编程

标签 c string function

我需要编写一个函数来计算字符串中的单词数。为了 这个任务的目的,一个“词”被定义为一个序列 非空,非空白字符,与其他单词分开 空格。

这是我目前所拥有的:

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 循环使用 ; 而不是 ,


在没有任何免责声明的情况下,我会这样写:

现场观看 http://ideone.com/uNgPL

#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/

相关文章:

c++ - 复合日期类型的调用约定

c++ - 在 C/C++ 中,左移或右移零实际上会生成一条指令吗?

c - 在 C 中,解析由多个空格分隔的整数组成的字符串

Python 从 DataFrame 字符串字段中去除所有空格

javascript - 如果多个动画完成,如何从函数返回

function - 这个 `init` 的实现是如何工作的?

c - 如何将文本文件转换为字符串,但在 C 中包含 "\n"?

c - 为什么变量声明在括号外

Java RegEx - 非法字符点

c - 在 Assembly Works 中如何调用带有大量参数的函数