c - 计算C中一串数字中出现频率最高的数字
问题描述
我正在尝试计算字符串中最常见的数字,我需要使用指针,但我不确定如何使用指针来解决这个问题。
int most(char* string){
int counter = 0;
int* array =(int*) malloc(sizeof(int)*10);
char* original = string;
while(*original){
counter++;
string++;
//Not sure what to put in this loop
}
}
例如,我想调用代码
char nums[] = "132433423";
printf("%d \n",most(nums));
// 3
解决方案
您的功能规范不完整:
- 字符串可以包含非数字字符吗?
- 如果根本没有数字应该返回什么?
- 如果有多个数字具有相同的最大出现次数,应该返回哪个值?
- 该函数应该返回数字还是它的数值?您的
main()
函数使用后者,但从问题的文本中不清楚。
该most
函数接收一个指向字符串的指针。您可以编写一个循环,一次处理一个字符,并为下一次迭代递增指针,直到到达字符串的末尾。如果字符串不包含数字,您还必须决定返回什么。
这是一个简单的例子:
int most(const char *s) {
int count[10] = { 0 };
int res, i, max;
while (*s) {
if (*s >= '0' && *s <= '9')
count[*s - '0']++;
s++;
}
res = -1; /* return -1 if no digits */
max = 0;
for (i = 0; i < 10; i++) {
if (count[i] > max)
res = i;
}
return res;
}
如果您完全不能使用任何数组,那么分配一块内存似乎确实是一个不错的解决方案:
int most(const char *s) {
int *count = calloc(sizeof(*count), 10);
int res, i, max;
while (*s) {
if (*s >= '0' && *s <= '9')
*(count + *s - '0') += 1;
s++;
}
res = -1; /* return -1 if no digits */
max = 0;
for (i = 0; i < 10; i++) {
if (*(count + i) > max)
res = i;
}
free(count);
return res;
}
该符号以*(count + *s - '0') += 1
这种方式工作:是指向分配并初始化为bycount
的数组的指针。是 所指向的字符的数字值 n ,已被测试为数字。是指向数组中第 n 个条目的指针。将此值加一。int
0
calloc
*s - '0'
s
count + *s - '0'
*(count + *s - '0') += 1
有一些方法可以在没有内存分配的情况下做到这一点,有 10 个变量和对不同数字的显式测试,但我怀疑这是预期的解决方案。
如果您可以向老师解释您的选择,有两种方法可以使用不带[
and]
字符的数组。这些是 C 标准的过时特性,大多数程序员都不熟悉,除非你好奇,否则可以忽略它们:
int most(const char *s) { /* version with C99 digraphs */
int count<:10:> = { 0 };
int res, i, max;
while (*s) {
if (*s >= '0' && *s <= '9')
count<:*s - '0':>++;
s++;
}
res = -1; /* return -1 if no digits */
max = 0;
for (i = 0; i < 10; i++) {
if (count<:i:> > max)
res = i;
}
return res;
}
或者
int most(const char *s) { /* version with old-style trigraphs */
int count??(10??) = { 0 };
int res, i, max;
while (*s) {
if (*s >= '0' && *s <= '9')
count??(*s - '0'??)++;
s++;
}
res = -1; /* return -1 if no digits */
max = 0;
for (i = 0; i < 10; i++) {
if (count??(i??) > max)
res = i;
}
return res;
}
推荐阅读
- php - PHP从同名的xml节点中提取数据
- r - 使用 R 从 URL 下载多个文件不起作用
- linux - 如何在 Linux 启动期间自动启动此应用程序?
- firebase - 在 firebase 中使用两个令牌的目的是什么?- 服务器客户端 Web 应用程序的 firebase 身份验证查询
- java - 通过双击启动 selenium-server-standalone-3.141.59.jar 与命令行 java -jar selenium-server-standalone-3.141.59.jar 时的差异
- ios - 错误:“可选”类型的值
' 在 Swift iOS 中没有下标数组 [0] - python - 如何使用 Python 从一次性音频样本中获取 hz 音符?
- c# - EF Core:错误无法修改 OwnsOne 属性
- python - 如何正则表达式最后一个/(如果存在不止一次)
- php - 如何根据给定值对数据进行优先级排序