fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6.  
  7. #define MAX_NAME_LEN 50
  8. #define MAX_LINE_LEN 500
  9.  
  10. typedef struct {
  11. char name[MAX_NAME_LEN];
  12. int number;
  13. } Fruit;
  14.  
  15. void toLowerCase(char *s) {
  16. for (int i = 0; s[i]; i++)
  17. s[i] = (char)tolower((unsigned char)s[i]);
  18. }
  19.  
  20. void capitalize(char *s) {
  21. if (s[0]) s[0] = (char)toupper((unsigned char)s[0]);
  22. for (int i = 1; s[i]; i++)
  23. s[i] = (char)tolower((unsigned char)s[i]);
  24. }
  25.  
  26. int cmp(const void *a, const void *b) {
  27. Fruit *fa = (Fruit*)a;
  28. Fruit *fb = (Fruit*)b;
  29. return fb->number - fa->number;
  30. }
  31.  
  32. int main() {
  33. char line[MAX_LINE_LEN];
  34. if (!fgets(line, MAX_LINE_LEN, stdin)) return 1;
  35. line[strcspn(line, "\n")] = 0;
  36.  
  37. int capacity = 10, len = 0;
  38. Fruit *fruits = (Fruit*)calloc(capacity, sizeof(Fruit));
  39. if (!fruits) return 1;
  40.  
  41. char *token = strtok(line, ", .");
  42. while (token) {
  43. toLowerCase(token);
  44. bool found = false;
  45. for (int i = 0; i < len; i++) {
  46. if (strcmp(fruits[i].name, token) == 0) {
  47. fruits[i].number++;
  48. found = true;
  49. break;
  50. }
  51. }
  52. if (!found) {
  53. if (len == capacity) {
  54. capacity *= 2;
  55. Fruit *temp = realloc(fruits, capacity * sizeof(Fruit));
  56. if (!temp) { free(fruits); return 1; }
  57. fruits = temp;
  58. }
  59. strncpy(fruits[len].name, token, MAX_NAME_LEN - 1);
  60. fruits[len].name[MAX_NAME_LEN - 1] = '\0';
  61. fruits[len].number = 1;
  62. len++;
  63. }
  64. token = strtok(NULL, ", .");
  65. }
  66.  
  67. qsort(fruits, len, sizeof(Fruit), cmp);
  68.  
  69. printf("%-15s\t%-8s\n", "Fruit", "Freq");
  70. for (int i = 0; i < len; i++) {
  71. capitalize(fruits[i].name);
  72. printf("%-15s\t%-8d\n", fruits[i].name, fruits[i].number);
  73. }
  74.  
  75. free(fruits);
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 5320KB
stdin
Apple, Mango, Orange, apple, pineapple, apple, banana, mango, banana, banana
stdout
Fruit          	Freq    
Apple          	3       
Banana         	3       
Mango          	2       
Orange         	1       
Pineapple      	1