计数的话在一个字符串 - c编程 [英] Counting words in a string - c programming

查看:96
本文介绍了计数的话在一个字符串 - c编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数,将字符串中的数字。为了
这个分配,一个字的目的被定义为一个序列
非空,无空白字符,由换句话说分离
空白。

I need to write a function that will count words in a string. For the purpose of this assignment, a "word" is defined to be a sequence of non-null, non-whitespace characters, separated from other words by whitespace.

这是我迄今为止:

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;

我不知道是否可行与否,因为我无法测试它,直到我的整个程序完成,我不知道它会工作,有没有写这个功能的一个更好的办法?

I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?

推荐答案

您需要

int words(const char sentence[])
{
}

(注意括号)。

有关循环去与; 而不是

在没有任何声明,这里就是我想要写:

Without any disclaimer, here's what I'd have written:

实时查看 http://ideone.com/uNgPL

See it live 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编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆