c - 如何计算C中相同字符的个数?

标签 c arrays string char strlen

我正在编写一个提示用户输入字符串的代码

&

创建一个 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;
}

我也得到了错误的输出。

输出:

输入字符串你好 最常见的字符是:'h',出现 2 次 使用了 5 个字符

应该是

出现频率最高的字符是:'l',出现了 2 次 使用了 5 个字符

最佳答案

简而言之(如果我写错了其他人会纠正我^_^) 你声明一个 int 是这样的:

int var;

像这样使用它:

var = 3;

你像这样声明一个指针:

int* pvar;

并像这样使用指向的值:

*pvar = 3;

如果您声明了一个变量并需要将指针作为函数参数传递给它,请像这样使用 & 运算符:

functionA(&var);

或者简单地将其地址保存在指针变量中:

pvar = &var;

这是基础。我希望它能帮助...

关于c - 如何计算C中相同字符的个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174135/

相关文章:

c - 将二进制数拆分为数字

c - 防止读取和返回字符串值

c - 数组初始值设定项之间的区别

arrays - 集合的完全和部分匹配

C:在 0x0FFB0BA0 处抛出异常(ucrtbased.dll)

JavaScript正则表达式测试函数: *OR* syntax

c - 从文件中读取行并将它们拆分为数组

C 编程代码(帮助)

string - 如何通过telnet或任何其他程序将字符串数据发送到套接字连接?

python - 在 Python 中将字符串列表转换为元组