Advertisement
CSenshi

Programming Paradigms (MT. 2017) - ex. 2

Oct 16th, 2019
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include "fix_text.h"
  2.  
  3. int cmp(const void *w1, const void *w2)
  4. {
  5.     char *elem1 = *(char **)w1;
  6.     char *elem2 = *(char **)w2;
  7.     return strcmp(elem1, elem2);
  8. }
  9.  
  10. void spellCorrect(char **lex, size_t n, char **sent)
  11. {
  12.     int ind = 0, start_ind = 0;
  13.     while ((*sent)[ind] != '\0')
  14.     {
  15.         // get 1 word
  16.         start_ind = ind;
  17.         while ((*sent)[ind] != ' ' && (*sent)[ind] != '\0')
  18.             ind++;
  19.  
  20.         // copy word to cur_word
  21.         int word_len = ind - start_ind;
  22.         char *cur_word = malloc(word_len + 1);
  23.         memcpy(cur_word, (*sent) + start_ind, word_len);
  24.         cur_word[word_len] = '\0';
  25.  
  26.         // search if cur_word is in lex;
  27.         void *ptr = bsearch(&cur_word, lex, n, sizeof(char *), cmp);
  28.  
  29.         // if found do nothing, it's correct!
  30.         if (ptr)
  31.         {
  32.             ind++;
  33.             continue;
  34.         }
  35.  
  36.         // else substitue last char
  37.         int base_ind = ind - 1;
  38.         int left_len = strlen((*sent) + base_ind + 1);
  39.  
  40.         // copy everything from next space till the end into the current word's last char
  41.         memcpy((*sent) + base_ind, (*sent) + base_ind + 1, left_len + 1);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement