2016-03-10 47 views
0
#include <string.h> 
#include <stdio.h> 
#include <ctype.h> 
#define SIZE 100 

const char delim[] = ", . - !*()&^%$#@<> ? []{}"; 

int main(void) 
{ 
int length[SIZE] = { 0 }; 
int name[SIZE]; 
int i = 0, ch; 
int wordlength = 0; 
int occurence = 0; 

printf("Please enter sentence, end the setence with proper punctuation(! . ?) : "); 

while (1) 
{ 
    ch = getchar(); 

    if (isalpha(ch)) 
    { 
     ++wordlength; 
    } 
    else if (strchr(delim, ch)) 
    { 
     if (wordlength) 
     { 
      length[wordlength - 1]++; 
     } 

     if(ch == '.' || ch == '?' || ch == '!') 
     { 
      break; 
     } 

     if(ch == '\'') 
     { 
      wordlength++; 
     } 

     wordlength = 0; 
    } 
} 

printf("Word Length \tOccurence \n"); 

for(i = 0; i<sizeof(length)/sizeof(*length); ++i) 
{ 
    if(length[i]) 
    { 
     printf(" %d \t\t%d\n", i + 1, length[i]); 
    } 
} 

return 0; 
} 

所以程序应该算冒了一句,如...字长度计不计算单引号为字符

"Hello how are you?" 

然后输出:

5 Letter Words -> 1 
    3 Letter Words -> 3 

不过我希望它也可以将单引号计为一个字符,例如...

输入:

​​

输出:

4 Letter words -> 2 

我已经尝试使用...

if(ch == '\'') 
     { 
      wordlength++; 
     } 

但它只是不计数单引号的字符。

+0

为什么你需要逃脱单引号? –

回答

2

您错过了continue从您的if (ch =='\'') { ... };这就是为什么wordlength之后立即归零的原因。

另一种解决方案是包括在第一if条件'

if (isalpha(ch) || ch == '\'') { 
    wordlength ++; 
} 
+0

是的,工作,谢谢! – bobblehead808