【C程序】字符串拆分子串传入传出接口函数×2

来源:互联网 发布:linux mv 文件夹 编辑:程序博客网 时间:2024/06/04 00:37
/* 优点:效率高,纯指针操作 */#include <stdio.h>#include <ctype.h>#include <string.h>#define LEN 10static int split_string (char *src_str, char dest_str[][LEN]){int index = 0;char *ph = src_str;char *p  = src_str;if(!src_str)return -1;/* *p != NULL && *p != 空格 */while(*p && isspace(*p) == 0){if(index > 9)return -1;if(*(++p) == ',' || *p == '\0' || isspace(*p)){memcpy(dest_str[index], ph, (p - ph));index++;ph = p+1;//printf ("dest_str[%d]=%s.\n",index-1,dest_str[index-1]);}}return 0;}int main (void){char *p = "111,222,333,aaa,bbb,ccc";char test_buf[LEN][LEN] = {0};int i = 0;split_string (p, test_buf);for (i = 0; i < 10 && strlen (test_buf[i]); i++)printf ("test_buf[%d] = %s\n", i, test_buf[i]);return 0;}

/* 优点:分隔符可通过参数传递 */#include <stdio.h>#include <ctype.h>#include <string.h>#define LEN 10static int strtok_string (char *src_str, char dest_src[][LEN], char *delim){int i = 0;char *p = NULL;p = strtok (src_str, delim);snprintf (dest_src[i], strlen (p)+1, "%s", p);while (p = strtok (NULL, delim)) {i++;snprintf (dest_src[i], strlen (p)+1, "%s", p);}return 0;}int main (void){char s[] = "111,222,333,aaa,bbb,ccc";char *delim = ",";char test_buf[LEN][LEN] = {0};int i = 0;strtok_string (s, test_buf, delim); // test_buf type: char (*)[]for (i = 0; i < LEN && strlen (test_buf[i]); i++)printf ("test_buf[%d] = %s\n", i, test_buf[i]);return 0;}

验证效果:


原创粉丝点击