티스토리 뷰

Devolopment/C, C++

string_explode()

OpenUiz 2015. 5. 29. 14:25
반응형

예를들어, 

// ...
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;
}

 

 

주의) 넘겨받은 result는 꼭 free시켜주어야 한다.

참고: http://openuiz.tistory.com/51

반응형
반응형
최근에 달린 댓글