c - 如何计算C中相同字符的数量?
问题描述
我正在编写一个提示用户输入字符串的代码
&
创建一个类型为 void 的函数,该函数打印出使用最多的字符
(就像它出现的地方比其他任何地方都多)
&
还显示了它在该字符串中的次数。
因此,这就是我到目前为止所拥有的......
#include <stdio.h>
#include <string.h>
/* frequent character in the string along with the length of the string (use strlen from string.h – this will require you to #include <string.h> at the top of your program).*/
/* Use array syntax (e.g. array[5]) to access the elements of your array.
* Write a program that prompts a user to input a string,
* accepts the string as input, and outputs the most
* You should implement a function called mostfrequent.
* The function prototype for mostfrequent is: void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts);
* Hint: Consider the integer value of the ASCII characters and how the offsets can be translated to ints.
* Assume the user inputs only the characters a through z (all lowercase, no spaces).
*/
void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
int array[255] = {0}; // initialize all elements to 0
int i, index;
for(i = 0; most_freq[i] != 0; i++)
{
++array[most_freq[i]];
}
// Find the letter that was used the most
qty_most_freq = array[0];
for(i = 0; most_freq[i] != 0; i++)
{
if(array[most_freq[i]] > qty_most_freq)
{
qty_most_freq = array[most_freq[i]];
counts = i;
}
num_counts_++;
}
printf("The most frequent character was: '%c' with %d occurances \n", most_freq[index], counts);
printf("%d characters were used \n", num_counts_);
}
int main()
{
char array[5];
printf("Enter a string ");
scanf("%s", array);
int count = sizeof(array);
mostfrequent(count , array, 0, 0);
return 0;
}
我也得到了错误的输出。
输出:
输入字符串 hello 最常见的字符是:'h' 出现 2 次 使用了 5 个字符
应该
最常见的字符是: 'l' 出现 2 次 使用了 5 个字符
解决方案
让我们简短一点(如果我写错了,其他人会纠正我 ^_^ )你声明一个这样的 int :
int var;
像这样使用它:
var = 3;
你声明一个这样的指针:
int* pvar;
并像这样使用指向的值:
*pvar = 3;
如果您声明了一个变量并需要将一个指针作为函数参数传递给它,请像这样使用 & 运算符:
functionA(&var);
或者只是将其地址保存在指针 var 中:
pvar = &var;
这就是基础。我希望它会有所帮助...
推荐阅读
- python - 如何在 Python Pandas 中增加 countplot 的字体大小?
- sql - VBA代码中WHERE关键字的正确语法语法是什么
- python - MLflow:INVALID_PARAMETER_VALUE:模型注册表存储不支持 URI './mlruns'
- powershell - 为什么我的 foreach 列表中的第一项作为 $i 运行最终是空白或与列表中的下一项混合?
- amazon-web-services - Cloudformation - 在地图中定义默认值
- javascript - div没有将 html标签之间的文本转换为真正的粗体文本
- c# - 尝试从 NetCore50 exe WPF 项目引用 Netcore50 库 WPF 项目时无法加载文件或程序集
- excel - 在条件格式下引用论坛中的当前行
- javascript - Stripe 出错,在 localhost 上有效,但在服务器上无效
- c# - 如何正确处理玩家和两个重叠墙 XNA 之间的碰撞