C 编程 - 分析字符串中的散文?

标签 c

如果给出以下字符散文:

"Hope is the thing with feathers
That perches in the soul
And sings the tune without the words
And never stops at all”

如何计算字符串的长度和空格数?这是我迄今为止所拥有的:

#include <stdio.h>
#include <ctype.h>
int count(char *string);
int main(void){
    char prose[ ] =
        "Hope is the thing with white feathers\n"
        "That perches in the soul.\n"
        "And sings the tne without the words\n"
        "And never stops at all.";
    printf("count of word : %d\n", count(&prose[0]));
    return 0;
}
char *NextWordTop(char *string){
    static char *p = NULL;
    char *ret;
    if(string)
        p = string;
    else if(!p)
        return NULL;
    while(isspace(*p))++p;
    if(*p){
        ret = p;
        while(!isspace(*p))++p;
    } else
        ret = p = NULL;
    return ret;
}
int count(char *str){
    int c = 0;
    char *p;
    for(p=NextWordTop(str); p ; p=NextWordTop(NULL))
        ++c;
    return c;
}

最佳答案

#include <stdio.h>
#include <ctype.h>

int main(void){
    char prose[ ] =
        "Hope is the thing with white feathers\n"
        "That perches in the soul.\n"
        "And sings the tne without the words\n"
        "And never stops at all.";
    int len, spc;
    char *p = prose;
    for(len=spc=0;*p;++p){
        ++len;
        if(isspace(*p))//if(' ' == *p)
            ++spc;
    }
    printf("length : %d\t spaces : %d\n", len, spc);
    //length : 123     spaces : 23
    return 0;
}

关于C 编程 - 分析字符串中的散文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204062/

相关文章:

c - 发送数据包时如何设置iptables标记?

c - 如何避免多个原始套接字绑定(bind)到同一 IP 地址?

c - 优雅地退出多线程进程

c++ - 您如何在 C 预处理器中使用定义进行逻辑异或

c - 如何重现 C99 中的类方法行为?

c - 使用 `##` 运算符的串联问题

c - 在 C 中实现(包含)过滤器的最佳方式

c - 正在检测 TFTP 数据的传入端口?

c - 1- 在 C 中创建一个库 2- 在 MASM 中调用并使用它

c - 这些嵌套的 `for` 循环在 C 语言中如何工作?