首页 > 解决方案 > 如何计算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 个字符

标签: carraysstringcharstrlen

解决方案


让我们简短一点(如果我写错了,其他人会纠正我 ^_^ )你声明一个这样的 int :

int var;

像这样使用它:

var = 3;

你声明一个这样的指针:

int* pvar;

并像这样使用指向的值:

*pvar = 3;

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

functionA(&var);

或者只是将其地址保存在指针 var 中:

pvar = &var;

这就是基础。我希望它会有所帮助...


推荐阅读