#内容
hackerrankの問題から
document→paragraph(改行区切り)→sentence(ピリオド区切り)→word(スペース区切り)
メモ用なので、関数化前&コメントなし
もうちょっと練ってから書き始めればよかった。
似たような操作しかないので、しっかり練ったら芸術的なプログラムになりそう
#コード
split.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char**** get_document(char* text) {
char**** result;
//result = malloc(sizeof(char)*strlen(text));
//char* buf = malloc(sizeof(char)*strlen(text));
char** split_para = malloc(sizeof(char*)*5);
int index_para=0;
char* ptr;
ptr = strtok(text,"\n");
while(ptr != NULL){
split_para[index_para] = malloc(sizeof(char)*strlen(ptr));
strcpy(split_para[index_para],ptr);
index_para++;
ptr = strtok(NULL,"\n");
}
char*** split_sentence = malloc(sizeof(char**)*index_para);
int index_sentence = 0;
for(int i=0;i<index_para;i++){
index_sentence = 0;
ptr = strtok(split_para[i],".");
while(ptr != NULL){
split_sentence[i] = realloc(split_sentence[i],sizeof(char*)*(index_sentence+1));
split_sentence[i][index_sentence] = malloc(sizeof(char)*strlen(ptr));
strcpy(split_sentence[i][index_sentence],ptr);
index_sentence++;
ptr = strtok(NULL,".");
}
}
free(split_para);
char**** split_word = malloc(sizeof(char***)*index_para);
int index_word = 0;
for(int i=0;i<index_para;i++){
index_sentence = 0;
while(split_sentence[i][index_sentence] != NULL){
split_word[i] = realloc(split_word[i],sizeof(char**)*(index_sentence+1));
index_word = 0;
ptr = strtok(split_sentence[i][index_sentence]," ");
while(ptr != NULL){
split_word[i][index_sentence] = realloc(split_word[i][index_sentence],sizeof(char*)*(index_word+1));
split_word[i][index_sentence][index_word] = malloc(sizeof(char)*strlen(ptr));
strcpy(split_word[i][index_sentence][index_word],ptr);
index_word++;
ptr = strtok(NULL," ");
}
index_sentence++;
}
}
free(split_sentence);
result = split_word;
return result;
}