Querying the Document

  • + 0 comments
    char* kth_word_in_mth_sentence_of_nth_paragraph(char**** document, int k, int m, int n) {
        return document[n-1][m-1][k-1];
    }
    
    char** kth_sentence_in_mth_paragraph(char**** document, int k, int m) { 
        return document[m-1][k-1];
    }
    
    char*** kth_paragraph(char**** document, int k) {
        return document[k-1];
    }
    
    char**** get_document(char* text) {
        int count_word = 0;
        int count_sentence = 0;
        int count_paragraph = 1;
        int len = strlen(text);
        for(int i = 0; i < len; i++)
        {
            if(text[i] == ' ')
                count_word++;
            else if(text[i] == '.')
            {
                count_word++;
                count_sentence++;
            }
            else if(text[i] == '\n')
                count_paragraph++;
        }
        char** words = (char**) malloc(count_word * sizeof(char*));
        words[0] = text;
        char*** sentences = (char***) malloc(count_sentence * sizeof(char**));
        sentences[0] = words;
        char**** paragraphs = (char****) malloc(count_paragraph * sizeof(char***));
        paragraphs[0] = sentences;
        
        for(int i = 1, i_word = 1, i_sentence = 1, i_paragraph = 1; i < len; i++)
        {
            if(text[i] == ' ')
            {
                text[i] = '\0';
                words[i_word++] = text+i+1;
            }
            else if(text[i] == '.')
            {
                text[i] = '\0';
                if(i_sentence < count_sentence && text[i+1] != '\n')
                {
                    words[i_word++] = text+i+1;
                    sentences[i_sentence++] = words + i_word - 1;
                }
            }
            else if(text[i] == '\n')
            {
                words[i_word++] = text+i+1;
                sentences[i_sentence++] = words + i_word - 1;
                paragraphs[i_paragraph++] = sentences + i_sentence -1;
            }
        }
        return paragraphs;
    }