计算字符在

时间:2017-10-16 20:05:03

标签: c arrays char

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 100

int main()
{

    int count[26] = {0};
    int i;
    char ch ='a';

    printf("Enter a sentence (end by '.'): ");

    while (ch != '.') {
        ch = getchar();

        count[(tolower(ch) - 'a')]++; 

        for (i = 0; i < 26; i++) {
            printf("'%c' has %2d occurrences.\n", i + 'a', count[i]); 
        }
    }       

    return 0;
}

该程序完成它应该做的事情。计数器工作正常的问题是程序运行每两个字母两次并打印出哪些字母出现0次。正确的输出应如下:

输入一个以'。'结尾的句子。

scanf读取此内容。

正确输出:

T发生1次

H发生1次

我发生了1次

S发生1次

但代码的输出遍历每一个字母,并打印出根本没有出现的字母。我需要摆脱出现“0次”的字母,只显示出现1次或更多次的字母。

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:0)

只需要一个简单的if来检查计数是否大于0:

for (i = 0; i < 26; i++) {
    if (count[i] > 0)
    {
        printf("'%c' has %2d occurrences.\n", i + 'a', count[i]); 
    }
}

答案 1 :(得分:0)

以下对我有用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 100

int main()
{

    int count[26] = {0};
    int i;
    char ch ='a';

    printf("Enter a sentence (end by '.'): ");

    while (ch != '.') {
        ch = getchar();

        count[(tolower(ch) - 'a')]++;

        for (i = 0; i < 26; i++) {
            if (count[i] > 0) {
                printf("'%c' has %2d occurrences.\n", i + 'a', count[i]);
            }
        }
    }

    return 0;
}

答案 2 :(得分:0)

我建议您将输入读入字符数组,用inputfgets(),然后遍历各个字符。

请注意,fgets()会在您可能要移除的尾随\n(换行符)中读取。

char input[100];
fgets(input, sizeof(input), stdin);

您可以检查fgets()的返回值,看看它是否成功。它会在出错时返回NULL

请注意,fgets()也会将尾随换行符(\n)读入input

您可以将其删除,如

input[strlen(input)-1]='\0';

现在查看input中的每个字符。

for(i=0; input[i]!='.' && input[i]!='\0'; ++i)
{
    count[tolower(input[i])-'a']++;
}

您可以确保input中包含.

if(strchr(input, '.')!=NULL)
如果字符串中没有字符,

strchr()将返回NULL

最后按照你的方式打印结果。

for(i=0; i<26; i++)
{
    if(count[i]>0)
    {
        printf("\n%c has %2d.", i+'a', count[i]);
    }
}

答案 3 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 100

int main()

{

int count[26] = {0};
int i;
char ch ='a';

printf("Enter a sentence (end by '.'): ");

while (ch != '.') {
    ch = getchar();

    count[(tolower(ch) - 'a')]++;

    for (i = 0; i < 26; i++) {
        if (count[i] > 0) {
            printf("'%c' has %2d occurrences.\n", i + 'a', count[i]);
        }
    }
}

return 0;

}

相关问题