字长计数器不计算单引号作为字符

时间:2016-03-10 17:28:42

标签: c string counter

#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

但我希望它也将单引号计为字符,例如......

输入:

  " 'Tis good. "

输出:

 4 Letter words -> 2

我尝试过使用...

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

但它只是不把单引号算作一个角色。

1 个答案:

答案 0 :(得分:2)

continue遗失了if (ch =='\'') { ... };这就是为什么wordlength之后立即归零。

另一种解决方案是在'条件中包含if

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