You are viewing a single comment's thread. Return to all comments →
Well, this was easier to do after the other "querying the document" challenge:
int count_char(char* str, char c) { int count = 0; for (int i = 0; str[i]; i++) count += (str[i] == c); return count; } struct document get_document(char* text) { struct document Doc; Doc.paragraph_count = count_char(text, '\n') + 1; Doc.data = malloc(Doc.paragraph_count * sizeof(struct paragraph)); int i = 0, j = 0, k = 0; char *saveptr1, *saveptr2, *saveptr3; char* paragraph = strtok_r(text, "\n", &saveptr1); while (paragraph) { Doc.data[i].sentence_count = count_char(paragraph, '.'); Doc.data[i].data = malloc(Doc.data[i].sentence_count * sizeof(struct sentence)); j = 0; char* sentence = strtok_r(paragraph, ".", &saveptr2); while (sentence) { Doc.data[i].data[j].word_count = count_char(sentence, ' ') + 1; Doc.data[i].data[j].data = malloc(Doc.data[i].data[j].word_count * sizeof(struct word)); k = 0; char* word = strtok_r(sentence, " ", &saveptr3); while (word) { Doc.data[i].data[j].data[k].data = malloc(strlen(word) + 1); strcpy(Doc.data[i].data[j].data[k].data, word); k++; word = strtok_r(NULL, " ", &saveptr3); } j++; sentence = strtok_r(NULL, ".", &saveptr2); } i++; paragraph = strtok_r(NULL, "\n", &saveptr1); } return Doc; } struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n) { return Doc.data[n-1].data[m-1].data[k-1]; } struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m) { return Doc.data[m-1].data[k-1]; } struct paragraph kth_paragraph(struct document Doc, int k) { return Doc.data[k-1]; }
Seems like cookies are disabled on this browser, please enable them to open this website
Structuring the Document
You are viewing a single comment's thread. Return to all comments →
Well, this was easier to do after the other "querying the document" challenge: