2013-11-25 2 views
-1

Если дана следующая обугленная проза:C Программирование - анализ прозы в строке?

«Надежда есть вещь с перьями
Это окуни в душе
И поет мелодию без слов
и никогда не останавливается на всех»

Как подсчитать длину строки и количество пробелов? Вот что у меня есть до сих пор:

#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; 
} 
+2

Вы пытаетесь подсчитать количество слов? или количество символов? – woolstar

+0

Думаю, вы очень усложняете, что нужно делать с помощью 'NextWordTop' и' count'. –

+0

Вы должны избавиться от статической переменной в NextWordTop() и просто вызвать 'p = NextWordTop (p)' в выражении повторной инициализации цикла for. –

ответ

1
#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; 
} 
+0

Настолько проще! Спасибо за своевременный ответ! – user3000039

Смежные вопросы