【问题标题】:Counting words separated by symbols as two words将由符号分隔的单词计数为两个单词
【发布时间】:2014-11-02 18:25:30
【问题描述】:
#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 个单词。我将如何修改我的代码来做到这一点?

【问题讨论】:

  • 目前,您有空格和换行符作为分隔符。想想你如何将它扩展到其他角色。

标签: c character counting words


【解决方案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;
}

【讨论】:

  • 这些只适用于那些符号,对吧?其他符号呢?像?,@等?是否有更简单的代码可以做到这一点,还是我需要列出每个符号?
【解决方案2】:

只需按以下方式使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多