gpt4 book ai didi

将由符号分隔的单词计为两个单词

转载 作者:行者123 更新时间:2023-11-30 19:18:28 24 4
gpt4 key购买 nike

#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个单词。我如何修改我的代码来做到这一点?

最佳答案

创建一个表示单词分隔的字符数组。修改 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;
}

关于将由符号分隔的单词计为两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com