2016-08-15 2 views
2

Хорошо, так что я имею прямо сейчас, проверяет количество слов. Но у меня возникают проблемы с сортировкой слов по алфавиту.Как отсортировать строки в алфавитном порядке в C?

Я предпочел бы сделать это, а затем просто посчитать количество, которым они являются.

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct node *node_ptr; 

typedef struct node { 
    int count; 
    char *word; 
    node_ptr next; 
} node_t; 

char *words[] = { "hello", "goodbye", "sometimes", "others", "hello", "others", NULL }; 

node_ptr new_node() { 
    node_ptr aNode; 

    aNode = (node_ptr)(malloc(sizeof(node_t))); 
    if (aNode) { 
     aNode->next = (node_ptr)NULL; 
     aNode->word = (char *)NULL; 
     aNode->count = 0; 
    } 
    return aNode; 
} 

node_ptr add_word(char *word, node_ptr theList) { 
    node_ptr currPtr, lastPtr, newPtr; 
    int result; 
    int found = 0; 

    currPtr = theList; 
    lastPtr = NULL; 
    printf("Checking word:%s\n", word); 

    if (!currPtr) { 
     newPtr = new_node(); 
     if (!newPtr) { 
      fprintf(stderr, "Fatal Error. Memory alloc error\n"); 
      exit(1); 
     } 
     newPtr->word = word; 
     newPtr->next = currPtr; 
     newPtr->count = 1; 
     found = 1; 
     theList = newPtr; 
    } 
    while (currPtr && !found) { 
     result = strcmp(currPtr->word, word); 
     if (result == 0) { 
      currPtr->count += 1; 
      found = 1; 
     } else 
     if (result>0) { 
      newPtr = new_node(); 
      if (!newPtr) { 
       fprintf(stderr, "Fatal Error. Memory alloc error\n"); 
       exit(1); 
      } 
      newPtr->word = word; 
      newPtr->next = currPtr; 
      newPtr->count = 1; 

      if (lastPtr) { 
       lastPtr->next = newPtr; 
      } else { 
       theList = newPtr; 
      } 
      found = 1; 
     } else { 
      lastPtr = currPtr; 
      currPtr = currPtr->next; 
     } 
    } 

    if ((!found) && lastPtr) { 
     newPtr = new_node(); 
     if (!newPtr) { 
      fprintf(stderr, "Fatal Error. Memory alloc error\n"); 
      exit(1); 
     } 
     newPtr->word = word; 
     newPtr->next = (node_ptr)NULL; 
     newPtr->count = 1; 
     lastPtr->next = newPtr; 
     found = 1; 
    } 
    return theList; 
} 

void printList(node_ptr theList) { 
    node_ptr currPtr = theList; 

    while (currPtr) { 
     printf("word: %s\n", currPtr->word); 
     printf("count: %d\n", currPtr->count); 
     printf("---\n"); 
     currPtr = currPtr->next; 
    } 
} 

int main() { 
    char **w = words; 
    node_ptr theList = (node_ptr)NULL; 

    printf("Start\n"); 
    while (*w) { 
     theList = add_word(*w, theList); 
     w++; 
    } 

    printList(theList); 
    printf("OK!\n"); 
    return 0; 
} 

Я также хотел бы вместо чтения из массива слов лучше читать из файла.

FILE *fp; 
fp = fopen("some.txt", "w"); 

Как читать из файла, используя мою структуру, которую я создал, а затем отсортировать?

Спасибо за помощь! Я пытаюсь научить себя C :)

+2

Это плохая привычка указатели: определение типа во 'ЬурейеЙ структуру узел * node_ptr;' Скрытие указателей не делает их более легкими для понимания или обработки, напротив, он запутывает ваш код. – chqrlie

+0

В 'add_word()', 'newPtr-> word = word;' проблема. Код, вероятно, должен добавить копию строки. – chux

+0

Извините за путаницу. Я хочу сделать как @WeatherVane .. Я бы хотел прочитать слова из файла и отсортировать их по алфавиту! – hiquetj

ответ

0

Вы можете прочитать слова из файла с fscanf():

int main(int argc, char *argv[]) { 
    node_t *theList = NULL; 
    for (int i = 1; i < argc; i++) { 
     FILE *fp = fopen(argv[i], "r"); 
     if (fp != NULL) { 
      char word[100]; 
      while (fscanf(fp, "%99s", word) == 1) { 
       theList = add_word(word, theList); 
      } 
      fclose(fp); 
     } 
    } 
    printList(theList); 
    printf("OK!\n"); 
    return 0; 
} 
+0

Что такое "линия" в вашем коде? в функции addword .. где вы инициализируете это? – hiquetj

+0

@hiquetj: извините, это была просто опечатка, я переименовал локальный массив 'word' и забыл этот экземпляр. Как вы можете видеть, я открываю файл с помощью 'fopen', читаю слова один за другим с помощью' fscanf() 'и добавляем их в список. Слова разделяются любым количеством пробельных символов, включая переводы строк. – chqrlie

+0

@hiquetj: этот ответ помог вам? Не возражаете ли вы принять его? – chqrlie

Смежные вопросы