2016-03-10 63 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