Created
October 1, 2018 21:09
-
-
Save SaitoAtsushi/e5c6c2b25c34530ab9bcea208aee1afa to your computer and use it in GitHub Desktop.
PHP の explode みたいなやつを C でやってみる遊び。 これの別解を考えてみた。 → https://qiita.com/1000VICKY/items/7456cf7f75b9b34dc3bd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdlib.h> | |
#include <iso646.h> | |
#include "explode.h" | |
static char** helper(char* str, const char* delim, size_t delim_size, size_t depth) { | |
char* matched_str = strstr(str, delim); | |
char** result; | |
if(matched_str) { | |
result = helper(matched_str+delim_size, delim, delim_size, depth+1); | |
if(not result) return NULL; | |
matched_str[0] = '\0'; | |
} else { | |
result = malloc((depth+1)*sizeof(char*)); | |
if(not result) return NULL; | |
result[depth+1] = NULL; | |
} | |
result[depth]=str; | |
return result; | |
} | |
char** explode(char* str, const char* const delim) { | |
return helper(str, delim, strlen(delim), 0); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char** explode(char*, const char*); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <iso646.h> | |
#include "explode.h" | |
int main(void) { | |
// 被分割文字列 | |
char str[] = "あいうえお<区切り文字列>かきくけこ<区切り文字列>さしすせそ<区切り文字列>たちつてと<区切り文字列>なにぬねの<区切り文字列>はまやらわ<区切り文字列>やいゆえよ<区切り文字列>"; | |
char** str_list = explode(str, "<区切り文字列>"); | |
if(not str_list) { | |
printf("explode に失敗"); | |
return 0; | |
} | |
for(int i=0; str_list[i]; i++) printf("%s\n", str_list[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment