- 论坛徽章:
- 0
|
。用回调吧。。
//str.h
#ifndef __ROBOT_UTIL_STR_H__
#define __ROBOT_UTIL_STR_H__
/* description:contains common used string functions
* author:saite.tt@hotmail.com
* create at:2008-6-12 12:57
* */
typedef void *cb_func(const char *str, int i, void *param);
int split_str(const char *str, const char ch, cb_func callback_func,
void *param);
#endif
//str.c
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <assert.h>
#include "str.h"
int split_str(const char *str, const char ch, cb_func callback_func,
void *param)
{
char *t_str = NULL;
char *p = NULL;
char *t = NULL;
int i = 0;
assert(str);
t_str = (char *)malloc(strlen(str)+1);
if(!t_str){
return -1;
}
t = t_str;
strcpy(t_str, str);
p = t_str;
while(*p){
if(*p == ch){
*p++ = '\0';
callback_func(t,i++,param);
t = p;
}
else
p++;
}
callback_func(t,i,param);
if(t_str){
assert(t && p);
free(t_str);
t_str = t = p = NULL;
}
return 0;
}
void *callback_func(const char *str, int i, void *param)
{
char *p = (char *)param;
printf("%s\n",str);
if(p){
printf("%s\n",p);
}
}
int main()
{
split_str("hello,world,saite",',',callback_func, "saite.tt@hotmail.com" ;
return 0;
} |
|