2014-11-02 62 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; 
} 
相关问题