예를들어,
...
char **result = NULL;
...
siz = explode(buf, "|", &result);
...
라고하면 buf 변수의 데이터를 |로 나누어 배열포인터를 반환한다.
int i;
for(i=1; i<siz; i++){
fprintf(stderr, "%02d[%s]\n", i, result[i]);
}
int string_explode(char *text, char *split, char ***result) { int i=0, fi=128; int charCount=0; int totalCount=0; char *prevPoint=text; char *currPoint=NULL; char **ans=NULL; ans=(char**)malloc(sizeof(char*)*fi); do { currPoint=strstr(prevPoint, split); if(currPoint!=NULL){ totalCount=currPoint-text; if(prevPoint==text) charCount=totalCount; else charCount=currPoint-prevPoint; if(fi <= i) { ans=(char**)realloc( ans, sizeof(char*)*(i+fi)); fi+=128; } ans[i]=(char*)malloc(charCount); strncpy(ans[i], prevPoint, charCount); ans[i][charCount]='\0'; prevPoint=currPoint+strlen(split); } } while(currPoint!=NULL && ++i); if(i>0){ ans=(char**)realloc( ans, sizeof(char*)*(i+1)); charCount=strlen(text)-totalCount; ans[i]=(char*)malloc(charCount); strncpy(ans[i], prevPoint, charCount); ans[i][charCount]='\0'; ++i; *result=ans; } return i; } |
wndml) 넘겨받은 result는 꼭 free시켜주어야 한다.
댓글 없음:
댓글 쓰기