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

How to count the number of same character in 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;
}

我也得到了错误的输出。

输出:

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

应该是

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

简而言之(写错了别人会指正^_^) 你这样声明一个整数:

int var;

像这样使用它:

var = 3;

你这样声明一个指针:

int* pvar;

并像这样使用指向的值:

*pvar = 3;

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

functionA(&var);

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

pvar = &var;

这是基础知识。希望对你有所帮助...

您应该使用的函数原型似乎包含至少一个多余的参数。 (您有 main() 中可用的总字符数)。为了找到最常出现的字符(至少出现该次数的第一个字符),您需要提供的功能是:

  1. 要评估的字符串;
  2. 一个数组,其大小使每个元素都代表您要查找的最频繁值的范围(对于 ASCII 字符 128 很好,对于 unsigned char、[=17= 范围内的所有字符) ] 会做);最后
  3. 指向 return 频率数组中索引的指针,该索引保存最常用字符的索引(如果使用相同次数的多个字符,则为一组字符的第一个字符)。

在您的函数中,您的目标是遍历字符串中的每个字符。在频率数组(已初始化为全零)中,您将每个字符映射到频率数组中的一个元素,并在每次遇到该字符时递增该元素的值。例如对于 "hello",您将递增:

frequency['h']++;
frequency['e']++;
frequency['l']++;
frequency['l']++;
frequency['o']++;

完成后您可以看到,元素 frequency['l']; 将保存 2 的值。因此,当你完成后,你只需循环遍历频率中的所有元素,并找到包含最大值的元素的 index

if (frequency[i] > frequency[most])
   most = i;

(这也是为什么您将获得出现该次数的所有字符中的第一个。如果您更改为 >=,您将获得该组字符中的最后一个。此外,在您的角色中计数你忽略第 6 个字符,'\n',这对于单行输入很好,但对于多行输入你需要考虑你想如何处理它)

在你的情况下,总而言之,你可以做类似的事情:

#include <stdio.h>
#include <ctype.h>

enum { CHARS = 255, MAXC = 1024 };      /* constants used below */

void mostfrequent (const char *s, int *c, int *most)
{
    for (; *s; s++)     /* loop over each char, fill c, set most index */
        if (isalpha (*s) && ++c[(int)*s] > c[*most])
            *most = *s;
}

int main (void) {

    char buf[MAXC];
    int c[CHARS] = {0}, n = 0, ndx;

    /* read all chars into buf up to MAXC-1 chars */
    while (n < MAXC-1 && (buf[n] = getchar()) != '\n' && buf[n] != EOF)
        n++;
    buf[n] = 0;     /* nul-terminate buf */

    mostfrequent (buf, c, &ndx);    /* fill c with most freq, set index */
    printf ("most frequent char: %c (occurs %d times, %d chars used)\n",
            ndx, c[ndx], n);
}

(注意: 通过在比较中使用 isalpha() 它将处理两个 upper/lower 大小写字符,您可以通过简单地检查 upper/lower 大小写或只是将所有字符转换为一种大小写)

例子Use/Output

$ echo "hello" | ./bin/mostfreqchar3
most frequent char: l (occurs 2 times, 5 chars used)

(注意: 如果你使用 "heello",你仍然会收到 "most frequent char: e (occurs 2 times, 6 chars used)",因为 'e' 是两个字符中的第一个被看到的次数相同)

处理频率问题的方法有很多种,但本质上它们的工作方式都是一样的。对于 ASCII 字符,您可以捕获最频繁出现的字符及其在单个 int 数组和 int 数组中出现的次数,该数组包含最大值出现位置的索引。 (您实际上也不需要索引——它只是保存循环以在每次需要时查找它)。

对于更复杂的类型,您通常会使用一个简单的结构来保存计数和对象。例如,如果您正在寻找最频繁出现的 ,您通常会使用如下结构:

struct wfreq {
    char *word;
    int count;
}

然后您只需使用 struct wfreq 数组,就像您在此处使用 int 数组一样。检查一下,如果您还有其他问题,请告诉我。

这是我想到的。我搞砸了指针。

void mostfrequent(int *counts, char *most_freq, int *qty_most_freq, int num_counts_)
{
        *qty_most_freq = counts[0];
        *most_freq = 'a';
        int i;
 for(i = 0; i < num_counts_; i++)
 {

      if(counts[i] > *qty_most_freq)
           {
               *qty_most_freq = counts[i];
               *most_freq = 'a' + i;
           }
}
}
/* char string[80]
 * read in string
 * int counts[26]; // histogram
 * zero counts (zero the array)
 * look at each character in string and update the histogram
 */
int main()
{
int i;
int num_chars = 26;
int counts[num_chars];
char string[100];

/*zero out the counts array */
 for(i = 0; i < num_chars; i++)
 {
        counts[i] = 0;
 }
printf("Enter a string ");
scanf("%s", string);

for(i = 0; i < strlen(string); i++)
{
        counts[(string[i] - 'a')]++;
}

int qty_most_freq;
char most_freq;

mostfrequent(counts , &most_freq, &qty_most_freq, num_chars);
printf("The most frequent character was: '%c' with %d occurances \n", most_freq, qty_most_freq);
        printf("%d characters were used \n",  strlen(string));
        return 0;
}