2014-11-02 93 views
-1
#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
    unsigned long c; 
    unsigned long line; 
    unsigned long word; 
    char ch; 
    char lastch = -1; 

    c = 0; 
    line = 0; 
    word = 0; 

    while((ch = getchar()) != EOF) 
    { 
     C++; 
     if (ch == '\n') 
     { 
      line ++; 
     } 
     if (ch == ' ' || ch == '\n') 
     { 
      if (!(lastch == ' ' && ch == ' ')) 
      { 
       word ++; 
      } 
     } 
     lastch = ch; 
    } 
    printf("%lu %lu %lu\n", c, word, line); 
    return 0; 
} 

因此,此程序計算標準輸入中的字符,行數或單詞數。但其中一個要求是,由諸如!, - ,+等的任何符號分隔的單詞必須被認爲是2個單詞。我將如何修改我的代碼來做到這一點?將由符號分隔的單詞計爲兩個單詞

+0

這是功課? – 2014-11-02 18:31:36

+1

目前,您有空格和換行符作爲分隔符。想想你會如何將它擴展到其他角色。 – mafso 2014-11-02 18:34:38

回答

1

創建一個表示單詞分隔的字符數組。 修改while循環中的第二個if條件,以檢查ch是否存在於數組中,並且lastch不存在於該數組中。

修改後的代碼:

#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
unsigned long c; 
unsigned long line; 
unsigned long word; 
char ch; 
char lastch = -1; 
int A[256] = {0}; 

//Initialize the array indexes which are to be treated as separators. 
//Next check the presence of any of these characters in the file. 

A[' '] = 1; A['+'] = 1; A['!'] = 1; A['-'] = 1; A['\n'] = 1; 
c = 0; 
line = 0; 
word = 0; 

while((ch = getchar()) != EOF) 
{ 
    C++; 
    if (ch == '\n') 
    { 
     line ++; 
    } 
    if (A[ch] == 1) 
    { 
     if (!(A[lastch] == 1 && A[ch] == 1)) 
     { 
      word ++; 
     } 
    } 
    lastch = ch; 
} 
printf("%lu %lu %lu\n", c, word, line); 
return 0; 
} 
+0

這些僅適用於那些符號的權利?其他符號呢?像?,@等?是否有一個更簡單的代碼去做或我需要列出每一個符號? – user3880587 2014-11-02 21:11:49

0

只使用字符isalnum()函數以下列方式

#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
unsigned long c; 
unsigned long line; 
unsigned long word; 
char ch; 
char lastch = -1; 

c = 0; 
line = 0; 
word = 0; 

while((ch = getchar()) != EOF) 
{ 
    C++; 
    if(ch=='\n') 
     { 
     line++; 
     continue; 
     } 
    if (!isalnum(ch)) 
    { 
     word++; 
    } 
} 
printf("%lu %lu %lu\n", c, word, line); 
return 0; 
} 
相關問題