首页 > 解决方案 > C countLetter 函数

问题描述

所以我创建了一个函数,该函数当前计算字符串中所有单个小写字母,并将它们输出如下:

一个:3

乙:5

等等...

我正在努力获得将大写和小写字母相加的功能,以便两个值都有一个输出。例如,如果有 3 个 'a' 和 4 个 'A',那么 A / a 的输出应该是 7。目前只输出小写字符。

#include <stdio.h>

void countLetters(char * strings[])
{
int loweralphabet[26] = { 0 };
int upperalphabet[26] = { 0 };
int i, j;

for (i = 0; i <= 2; i++) {
    for (j = 0; strings[i][j] != '\0'; j++) {
        char c = tolower(strings[i][j]);
        if (c >= 'a' && c <= 'z') {
            loweralphabet[c - 'a']++;
        if (c >= 'A' && c <= 'Z') {
            upperalphabet[c - 'A']++;
        }
        }
    }
}
printf("\n");

for (i = 0; i < 26; i++) {
    printf("%c / %c: %d\n", ('a' + i), ('A' + i), loweralphabet[i], 
upperalphabet[i]);
}
printf("\n");

return 0;
}

int main()
{
char * strings[] = { "Is laid back living your thing, ",
                     "or are you an adrenaline junkie always seeking 
                      adventure ?",
                     "Are you a culture lover looking to learn new things or 
                      do you live for the night ?",
                     "Do your friends see you as a sports fanatic, ",
                     "or are you a frequent gig goer obsessed with music ? 
                     ",
                     "Whichever of these you identify with, x is the 
                      place where you can follow your interests ",
                     "as well as explore new passions.",
                     "" };
countLetters(strings);
}

如果我只是在打印函数中将两个计数相加,则在输出程序时会显示:在此处输入图像描述

标签: carrayscount

解决方案


        char c = tolower(strings[i][j]);
        if (c >= 'a' && c <= 'z') {
            loweralphabet[c - 'a']++;
        if (c >= 'A' && c <= 'Z') {

在第 1 行之后,第 4 行中的条件将永远不会被满足。此外,它永远不会被满足,因为它被放置在第 2 行的条件块中(即你已经确定它c是小写的,现在你检查它是否是大写的;当然不是) .

事实上,目前还不清楚你在挣扎什么。由于您的程序是现在编写的,它应该不区分大小写地计算字母。


推荐阅读