結構_ASCII出現頻率
user_3763047219
c_cpp
2 years ago
1.8 kB
7
Indexable
#include <stdio.h> #include <string.h> #include <limits.h> #include <stdlib.h> typedef struct pair { int frequency; char charASCII; } pair; void print(pair* myData) { int i; for (i = 0; i < 128; i++) (myData[i].frequency == 0) ? printf("") : printf("%d %d\n", myData[i].charASCII, myData[i].frequency); } int main() { struct pair* myData = (struct pair*)malloc(128 * sizeof(struct pair)); int i, len, flag = 0; char str[9999]; while ( gets_s(str) != NULL) { if (flag != 0) printf("\n"); flag++; for (int i = 0; i < 128; i++) { myData[i].frequency = 0; } len = strlen(str); for (int i = 0; i < len; i++) { myData[str[i]].charASCII = str[i]; myData[str[i]].frequency= myData[str[i]].frequency+1; } for (int i = 127; i >= 0; i--) { for (int j = 0; j < i; j++) { if (myData[j].frequency > myData[j + 1].frequency) { int temp1 = myData[j].charASCII; myData[j].charASCII = myData[j + 1].charASCII; myData[j + 1].charASCII = temp1; int temp2 = myData[j].frequency; myData[j].frequency = myData[j+1].frequency; myData[j+1].frequency = temp2; } else if (myData[j].frequency == myData[j + 1].frequency) { if (myData[j].charASCII < myData[j + 1].charASCII) { struct pair temp = myData[j]; myData[j] = myData[j + 1]; myData[j + 1] = temp; } } } } print(myData); } return 0; }
Editor is loading...