首页 > 解决方案 > 如何使用 struct 计算每个 char 数组的计数时间?

问题描述

struct Page{
 char data[50];
 int count = 0; // ?
};
Page page[50];

我不知道如何保存每个 char 数组的计数。

例如:

input: a c b
page[i].data[0] = a; // a_count = 1
page[i].data[1] = c; // c_count = 1
page[i].data[2] = b; // b_count = 1

我的想法是

paga[i].data[0].count++;

但是,我不知道如何用 struct 来实现。

标签: c

解决方案


count您需要一个数组来解决这个问题,而不是一个整数。因此,您可以Page通过以下方式定义:

typedef struct Page
{
    char data[50];
    int countChar[TOTAL_CHARS];
} Page;

现在,我们不能像在函数中那样简单地在结构中初始化数组。所以我们必须手动初始化countChar[]0但是,有一个技巧可以让您摆脱这个令人厌烦的过程。诀窍是使用这样的宏:

#define NEW_PAGE { "", {0} }

并以下列方式使用它:

Page page[50] = NEW_PAGE;

现在,您所要做的就是将字符映射到的索引countChar[]并将其值增加 1。这可以通过以下方式完成:

page[0].countChar[ch - 'a']++;

这里,ch是输入的字符。考虑到所有输入都是小写字母,减去chwith'a'将产生表示字符频率所需的索引ch。如果可能的值ch都是 ASCII 字符,我们将简单地替换'a''\0'并相应地更改大小countChar[]

这是一个测试这个想法的代码:

#include<stdio.h>
#define NEW_PAGE { "", {0} }
#define TOTAL_CHARS 26

typedef struct Page
{
    char data[50];
    int countChar[TOTAL_CHARS];
} Page;

int main()
{
    Page page[50] = NEW_PAGE;
    char input[] = "hello world";
    char ch;
    int i = 0;
    int frequency;

    while(input[i] != '\0')
    {
        ch = input[i];
        page[0].data[i] = ch;
        page[0].countChar[ch - 'a']++;
        i++;
    }

    for(i=0; i<TOTAL_CHARS; i++)
    {
        frequency = page[0].countChar[i];
        if(frequency != 0)
            printf("%c is present %d times\n", ('a'+i), frequency);
    }
    return 0;
}

推荐阅读