With the help of dynamic memory allocation in C language, the effect of Split function in VB is realized.function Description:
Function: Splits a string by one character
Parameter src: string to split
Parameter Delim: Splits the string by this character
Parameter ISTR: Use this struct to return the number of string arrays and strings that were split by the caller
Returns whether the split was successful
#include <stdio.h> #include <stdlib.h> #include <string.h>typedef struct {char **str; The PChar of string array size_t num; The number of string}istring;/** \split string by a char * * \param src:the string This you want to Split * \param del Im:split string by this char * \param istr:a srtuct to save String-array ' s PChar and string ' s amount. * \return whether or not to split string successfully * */int split (char *src, char *delim, istring* istr)//split buf{ int i; Char *str = NULL, *p = NULL; Char **data; (*istr). num = 1;str = (char*) calloc (strlen (SRC) +1,sizeof (char)); if (str = = NULL) return 0; data = (char**) calloc (1,sizeof (char *)); if (data = = NULL) return 0; str = src;data[0] = strtok (str, delim); for (i=1; p = strtok (NULL, Delim); i++) {(*ISTR). num++; data = (char**) realloc (data, (i+1) *sizeof (char *)); if (data = = NULL) return 0; Data[i] = p; } (*ISTR). str = data; Free (str); Freep); Free (data); You must to free it in the caller of function str = p = NULL; return 1;} int main () {int i; Char s[]= "DATA0|DATA1|DATA2|DATA3|DATA4|DATA5|DATA6|DATA7|DATA8"; Istring ISTR; if (Split (S, "|", &istr)) {for (i=0;i<istr.num;i++) printf ("%s\n", Istr.str[i]); Free (ISTR.STR); When you don ' t ues it,you must-to-free memory. } else printf ("Memory allocation failure!\n"); System ("pause"); return 0;}
Operation Result:
Data0
Data1
Data2
Data3
Data4
Data5
Data6
Data7
Data8
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C Language Implementation Split function