/*
* explode function like in PHP (realloc version)
* completed in 2012/3/21
* since 2012/3/21
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **explode(const char
*del, const char
*src, int *size);
int main(int
argc, char *argv[]) {
char
*str = "We will we will
rock you!";
char
**new_str;
int i, len;
printf("The original str:
%s\n", str);
new_str = explode("* ", str, &len);
printf("The length: %d\n",
len);
printf("After explode:\n");
for(i
= 0; i < len; i++){
printf("%s\n", new_str[i]);
}
system("pause");
return
0;
}
char **explode(const char
*del, const char
*src, int *size) {
int i = 0;
int idx_del;
int idx_src = 0;
int num_token = 0;
int last_pos = 0;
char
**des = NULL;
// get the token and doing explode
while(*(src+idx_src) != '\0') {
idx_del = 0;
while(*(del+idx_del) != '\0') {
if(*(src+idx_src) == *(del+idx_del)){
// increase the num of token
num_token++;
// re-allocate the space for 'des'
des = (char**)realloc(des, (num_token)*sizeof(char*));
// allocate in real time for the new string
des[i] = (char*)malloc((idx_src-last_pos+1)*sizeof(char));
// put the 'end of string' in the last item
des[i][idx_src-last_pos]
= '\0';
// copy the specific section to be the new string
strncpy(des[i++], src+last_pos, idx_src-last_pos);
// record the position for the next new string
last_pos = idx_src+1;
// exit the current loop
break;
}
idx_del++;
}
idx_src++;
}
num_token += 1;
// assign the num of token to
the variable from outside
*size
= num_token;
// don't forget the last one if there is
des[num_token-1] = (char*)malloc((idx_src-last_pos+1)*sizeof(char));
des[num_token-1][idx_src-last_pos]
= '\0';
strncpy(des[num_token-1],
src+last_pos, idx_src-last_pos);
return
des;
}
沒有留言:
張貼留言