c - 如何使用 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 来实现。
解决方案
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
是输入的字符。考虑到所有输入都是小写字母,减去ch
with'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;
}
推荐阅读
- serialization - Godot/Gdscript 实例的序列化
- python - Pycharm python AttributeError:模块'urllib3'没有属性'Request'
- facebook-login - 此应用目前无法解决 Facebook 登录问题,因为我们正在更新此应用的其他详细信息
- r - R 中的优化:Levenberg-Marquardt 在 minpack.lm 中使用 nls.lm:将“maxiter”重置为 1024
- reactjs - redux-form 的正确 state 类型 state
- python - Simpy:如何监控资源使用情况
- sql - 具有可变表值的 SQL 列
- asp.net-core - 在 localhost 上发布 Asp.net 核心项目的问题
- rabbitmq - Camel RabbitMQ 中的属性/功能类似于 Spring Cloud Stream 的 producer 和 consumer.prefix 属性?
- mysql - 在mysql中添加浮点值的问题