c - 如何获得与出现次数相对应的字母进行排序?

标签 c loops pointers bubble-sort

我正在 Ubuntu 中使用 GCC 制作一个小型 ANSI C 应用程序。该程序查找字符串中每个字母的出现次数值,然后根据出现次数对它们进行降序排序。

我的main.c文件:

/*
* preprocessor directives
*/
#include "bubbleSort.h"

/*
* global variables
*/
char Ar[] = "All Gaul is divided into three parts, one of which the Belgae inhabit, the Aquitani another, those who in their own language are called Celts, in our Gauls, the third. All these differ from each other in language, customs and laws. The river Garonne separates the Gauls from the Aquitani; the Marne and the Seine separate them from the Belgae. Of all these, the Belgae are the bravest, because they are furthest from the civilization and refinement of [our] Province, and merchants least frequently resort to them, and import those things which tend to effeminate the mind; and they are the nearest to the Germans, who dwell beyond the Rhine , with whom they are continually waging war; for which reason the Helvetii also surpass the rest of the Gauls in valor, as they contend with the Germans in almost daily battles, when they either repel them from their own territories, or themselves wage war on their frontiers. One part of these, which it has been said that the Gauls occupy, takes its beginning at the river Rhone ; it is bounded by the river Garonne, the ocean, and the territories of the Belgae; it borders, too, on the side of the Sequani and the Helvetii, upon the river Rhine , and stretches toward the north. From 'Caesar's Conquest of Gaul', Translator. W. A. McDevitte. Translator. W. S. Bohn. 1st Edition. New York. Harper & Brothers. 1869. Harper's New Classical Library. Published under creative commons and available at http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.02.0001";

/*
* main function
*/
int main(void) {
    /*array to hold count of each letter in alphabet*/
    int ABStats[ALPHABET_SIZE] = { 0 };

    /*array to hold letters of alphabet*/
    char chAlphabet[ALPHABET_SIZE] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

    /*pointers for use in finding frequency of characters*/
    char *pAr = Ar;
    char *pAlphabet = chAlphabet;
    int *pABStats = ABStats;

    GetFrequency(pAr, pABStats); /*get the frequency of each letter*/
    DisplayVHist(pABStats, ALPHABET_SIZE); /*display the frequency of each letter*/

    int i, j;
    for (i = ALPHABET_SIZE-1; i >= 0; i--) {
        for (j = 0; j < i; j++) {
            if (*(pABStats+j) < *(pABStats+j+1)) {
                Swap(pABStats+j, pABStats+j+1);
            }
        }
    }

    DisplayVHist(pABStats, ALPHABET_SIZE); /*display the frequency of each letter*/

    return EXIT_SUCCESS; /*return zero*/
}

我的 bubbleSort.c 文件:

/*
* preprocessor directives
*/
#include "bubbleSort.h"

/*
* functions
*/
int GetFrequency(char *pAr, int *pABStats) {
    int chNum = 0;
    for (; *pAr != '\0'; pAr++) { /*check if at the end of the array*/
        char ch = *pAr; /*store current letter as a char*/
        if (isalpha(ch)) /*if character is a letter*/
            chNum = (toupper(ch) - 'A'); /*return ascii code of specified letter*/
        pABStats[chNum]++; /*store ascii value in array and increment array*/
    }
    return chNum;
}

void DisplayVHist(int *pABStats, int size) {
    int i, j;
    const float lengthAr = strlen(Ar); /*store length of array as a float*/
    for (i = 0; i < size; i++) { /*for each letter in the alphabet*/
        float chPercent = 100 * (*pABStats / lengthAr); /*calculate percentage*/
        printf("'%c' --> %6.3f percent --> %3d occurances --> ", (i + 'A'), chPercent, *pABStats);
        for (j = 0; j < (*pABStats / 2); j++) { /*for every two values being pointed to by pointer*/
            printf("%c",'*'); /*print asterisk*/
        }
        printf("\n");
        pABStats++;
    }
}

void Swap(int *pA, int *pB) {
    int temp;
    temp = *pA;
    *pA = *pB;
    *pB = temp;
}

我的 bubbleSort.h 文件:

/*
* preprocessor directives
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define ALPHABET_SIZE 26

/*
* global variables
*/
extern char Ar[];

/*
* function prototypes
*/
int GetFrequency(char*, int*);
void DisplayVHist(int*, int);
void Swap(int*, int*);

它当前所做的是以降序对出现值进行排序,这正是我想要的,但是当我显示结果时,“A”将具有最高值,这是错误的。我希望字母以与出现次数相同的方式排序,以便出现次数最多的字母(即“E”)与其出现次数一起出现在列表的顶部。我创建了一个名为 chAlphabet 的字符数组,以防我需要它来实现此目的。

我需要为此应用程序使用指针,尽管这可能不是处理该应用程序的最有效方法。我还需要使用 bubbleSort.c 中的 Sort() 函数进行排序。

如有任何帮助,我们将不胜感激。我对 C 编程相当陌生。谢谢。

最佳答案

好的,现在已经可以交换 pABStats(每个字母的统计数据)了,现在您需要做的就是交换字母表。为此,您需要一个用于字母表的数组,就像 pABStats 一样,幸运的是您已经拥有了:chAlphabet

然后您需要一个用于交换的函数,就像您拥有的 Swap 函数一样,但这次它应该采用 char * 参数,例如,像这样:

//in bubbleSort.c

void SwapAlphabet( char *pA, char *pB ) {
    char temp;
    temp = *pA;
    *pA = *pB;
    *pB = temp;
}

调用此函数的方式与调用 Swap 函数的方式相同,可以在之后或之前,无论什么:

//inside the second for in main in main.c

if ( blabla ) {
    Swap( ... );
    SwapAlphabet( chAlphabet + j, chAlphabet + j + 1 ); // <-- added this
}

最后,为打印函数引入一个新的第三个参数,DisplayVHist,它将保存 main 中的 chAlphabet:

//in bubbleSort.c
void DisplayVHist( ..., ..., char *chAlphabet ) { ... }

//and in bubbleSort.h
void DisplayVHist( ..., ..., char* );

并使用 chAlphabet 作为 main 中的第三个参数来调用该函数:

//towards the end in main in main.c
DisplayVHist( ..., ..., chAlphabet );

我之前撒过谎,但这将是最后一部分。更改 DisplayVHistprintf 内的 (i + 'A'),以执行您已对 pABStats< 执行的操作 那里。应该是这样的:

//inside the DisplayVHist in bubbleSort.c

printf( "...", *chAlphabet, chPercent, *pABStats );
...
chAlphabet++;

应该是这样,除非我错过了我在这里所做的编辑。每当您需要任何进一步说明时,请随时询问。

关于c - 如何获得与出现次数相对应的字母进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22118159/

相关文章:

javascript - 如何创建带有警报和提示的 while 循环以避免空输入?

c - 写入结构时出现段错误

c++ - 交换基本类型的对象会抛出异常吗?

c - 栈函数调用问题

c - 标准 I/O 库的缓冲

c - 全局变量总是用零初始化吗?

c - 为什么我们在调用 bind() 时将 sockaddr_in 转换为 sockaddr?

list - 在 Scala 中向后迭代两个列表(不同长度)

c - 如果用户输入的长度超过 16 个字符,为什么我的 C 程序会打印两次消息?

c - C 中的指针及其对数组的解释