如何统计相同字母超过3个的单词数量

  • 本文关键字:3个 单词数 何统计 统计 c
  • 更新时间 :
  • 英文 :


我的程序计算有3个字母的单词的数量,但我需要计算有3个相同字母的单词的数量。我正在试着写一个程序来计算多于三个字母的单词的数量。当输入句号时,程序必须结束。我的代码可以工作,但是它给所有包含3个字母的单词打分

#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
int cont = 0, counterLargerThanThree = 0;
printf("Enter a phrase that ends with a period:n");
do {
c = getchar();
if (c != ' ' && c != '.') {
++cont;
} else {
if (cont == 3) {
counterLargerThanThree++;
}
cont = 0;
}
} while (c != '.');
printf("%i n", counterLargerThanThree);
system("pause");
return 0;
}

你所要做的就是修改递增结果的逻辑。

  • 当你采取一个角色除了space.,这意味着,当条件if (c != ' ' && c != '.')true,增加频率的字符
  • 在其他情况下,这意味着当上述条件为false时,检查您作为输入的最后一个单词是否具有3相同的字符。

示例代码:

int main()
{
char c;
int wordWithThreeSameLetter = 0;
int frequency[26];  // assuming there'll be only small letters in input
for(int i = 0; i < 26; i++)
{
frequency[i] = 0;   // initializing the count of every character
}
printf("Enter a phrase that ends with a period:n");
do
{
c = getchar();
if (c != ' ' && c != '.')
{
frequency[c - 'a']++;    // incrementing count of the character
}
else
{
for(int i = 0; i < 26; i++)
{
if(frequency[i] == 3) wordWithThreeSameLetter++;    // counting word with 3 same letter
frequency[i] = 0;   // initializing the count for future word
}
}
}
while (c != '.');
printf("%i n", wordWithThreeSameLetter);

system("pause");
return 0;
}

输入:

a
b
c

e
f
e
g
e

x
y
y
o
y
.

输出:2输入:

a
b
c

d
e
e
f
.

输出:0

注意:-

  • 由于您没有特别提到输入格式,我假设输入中只有small letter character,space.。所以以上代码只适用于这样的输入。

最新更新