SHARE
TWEET

Uva10420

AcerYue Jun 2nd, 2020 718 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX (75 + 1)
  6.  
  7. int cmp(const void *a, const void *b){
  8.     return strcmp(*(char **)a , *(char **)b);
  9. }
  10.  
  11. int main(){
  12.     const char separator[] = " ";
  13.     char **name = NULL, buffer[MAX], *temp = NULL;
  14.     int n_lines, i;
  15.     //輸入行數
  16.     scanf("%d", &n_lines);
  17.     //讀取'\n'用
  18.     getchar();
  19.     //分配二維字元陣列空間
  20.     name = (char **)malloc(n_lines * sizeof(char *));
  21.     //分配每行字串陣列空間並將字串放入name
  22.     for(i = 0; i < n_lines; i++){
  23.         //對每個字元陣列控制分配長度
  24.         name[i] = (char *)malloc(MAX * sizeof(char));
  25.         //字串放入暫存
  26.         gets(buffer);
  27.         //利用strtok分割字串,將暫存的第一個單字取出
  28.         temp = strtok(buffer, separator);
  29.         //將temp放入
  30.         strcpy(name[i], temp);
  31.     }
  32.     //快速排序函式
  33.     qsort((void *)name, n_lines, sizeof(char *), cmp);
  34.     for(i = 0; i < n_lines; i++){
  35.         int counter = 0, j = i;
  36.         //j從i到最後找排序後的字串陣列,直到出現不同字停止
  37.         for(; j < n_lines; j++)
  38.             if(!strcmp(name[i], name[j]))
  39.                 counter++;
  40.             else
  41.                 break;
  42.         printf("%s %d\n", name[i], counter);
  43.         //因為j++所以指標調整為j - 1
  44.         i = j - 1;
  45.     }
  46.     //釋放記憶體
  47.     for(i = 0; i < n_lines; i++)
  48.         free((void *)name[i]);
  49.     free((void *)name);
  50.     return 0;
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top