如何在字符串中打印下一个公共元素?

时间:2017-01-18 20:32:49

标签: c string

我写了一个程序,在字符串中找到一个共同的字母,我打算打印那封信,以及第二个最常见的字母,我该如何实现呢?

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

 #define MAX 10
 #define MAX_FREQ 256
int main()
{
    char string[MAX] = {0};

    int i = 0; 
    int freq[MAX_FREQ] = {0};

    printf("Enter a String: ");
    fgets(string, MAX, stdin);
    if(string[strlen(string)-1] == '\n') {string[strlen(string)-1] = 0;}

    for(i = 0; string[i]; i++)
    {
        freq[string[i]]++;
    }

    for(i = 0; i < MAX_FREQ; i++)
    {
        if(freq[i])
        {
            printf("Most common: %c, 2nd most common: %c\n", i, i-1);
        }
    }
    return (0);
}

感谢。

2 个答案:

答案 0 :(得分:2)

我认为代码中的注释足以让您理解。

// max - most common, snd - second most common
int max_freq = 0, snd_freq = 0;
char max_char, snd_char;

// iterate through frequency array
for (int i = 0; i < MAX_FREQ; i++)
{
    if (freq[i] > max_freq)
    {
        /*
         * we had a previous max_freq that satisfied max_freq > snd_freq
         * since we found a new freq > max_freq, we'll change snd_freq as well
         * to max_freq
         * order: freq[i] > max_freq > snd_freq
        */

        snd_freq = max_freq;
        max_freq = i; //it'll be converted, don't worry

        snd_char = max_char;
        max_char = str[i];
    }
    else if (freq[i] > snd_freq)
    {
        snd_freq = freq[i];
        snd_char = i;
    }
}

// print most and second most common characters
printf("%c %c", max_char, snd_char);

答案 1 :(得分:0)

使用如下代码: -

int max = INT_MIN , max2 = INT_MIN,maxi,max2i; //using <limits.h>   
for(i = 0; i < MAX_FREQ; i++)
{

    if(max<=freq[i])
    {
        max = freq[i];
        maxi =i;
    }

    if(freq[i]<=max && freq[i]=>Max && max1i! =i)
    {max2 = freq[i];
      max2i = i;
     }
}

现在您可以轻松使用max1i和max2i索引来打印这些字符