#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 1000
#define MAX_WORD_NUM 200
#define MAX_WORD_SIZE 40
typedef struct {
char word[3][MAX_WORD_SIZE];
} TRIPLET;
char* str_lower (char *str){
int ct = 0;
while (*(str + ct)) {
*(str + ct) = tolower(*(str + ct));
ct++;
}
return str;
}
int cmp_word(const void* n1, const void* n2) {
return strcmp(((TRIPLET*)n1)->word[1], ((TRIPLET*)n2)->word[1]);
}
int main(void)
{
FILE* fptr;
TRIPLET triplet[MAX_WORD_NUM];
char buf[BUF_SIZE], word[MAX_WORD_NUM][MAX_WORD_SIZE],* tp, *punc = " .,:&-";
int word_num = 0, ct, ct_sub;
// ファイルをオープン
if ((fptr = fopen("XA_1.txt", "r")) == NULL) {
printf("Unable to open file.\n");
return 1;
}
fgets(buf, BUF_SIZE, fptr); // 1行読み込み
fclose(fptr); // ファイルをクローズ
buf[strlen(buf) - 1] = '\0'; // 末尾の \n を消す
str_lower(buf); // 小文字に変換
// 単語に切り分け
printf("【単語】\n");
tp = strtok(buf, punc);
strcpy(word[word_num], tp);
printf("#%d: %s\n", word_num + 1, word[word_num]);
word_num++;
while (tp != NULL) {
tp = strtok(NULL, punc);
if (tp != NULL) {
strcpy(word[word_num], tp);
printf("#%d: %s\n", word_num + 1, word[word_num]);
word_num++;
}
}
printf("\n");
printf("単語数 = %d\n", word_num); // 単語数を表示
printf("\n");
// 3連語に格納
printf("【3連語】\n");
for (ct = 0; ct < word_num - 2; ct++) {
printf("#%d: ", ct + 1);
for (ct_sub = 0; ct_sub < 3; ct_sub++) {
strcpy(triplet[ct].word[ct_sub], word[ct + ct_sub]);
printf("%s ", triplet[ct].word[ct_sub]);
}
printf("\n");
}
// 3連語の中央の語をキーとして降順に並べ替え
qsort(triplet, word_num - 2, sizeof(TRIPLET), cmp_word);
// 結果の表示
printf("\n");
printf("【並べ替え】\n");
for (ct = 0; ct < word_num - 2; ct++) {
printf("#%d: %s %s %s\n", ct + 1, triplet[ct].word[0], triplet[ct].word[1], triplet[ct].word[2]);
}
return 0;
}
========
【実行結果】
【単語】
#1: eight
#2: schools
#3: looking
#4: toward
#5: the
(中略)
#93: set
#94: of
#95: viewpoints
#96: of
#97: things
単語数 = 97
【3連語】
#1: eight schools looking
#2: schools looking toward
#3: looking toward the
#4: toward the 21st
#5: the 21st century
(中略)
#91: a multidimensional set
#92: multidimensional set of
#93: set of viewpoints
#94: of viewpoints of
#95: viewpoints of things
【並べ替え】
#1: the 21st century
#2: students a multidimensional
#3: with a small
#4: business administration science
#5: courses aim to
(中略)
#91: gakuin university has
#92: at university another
#93: of viewpoints of
#94: courses which involve
#95: organized with a