slevy1ster
-
C,
pasted
on Nov 7:
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
size_t count = 0;
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
printf("Count is %d\n",count);
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
int i,j;
int max = 0;
char str[] = "1,2,3,\\n,4,5,6,\\n,7,8,9,\\n";
puts(str);
char ** result = str_split(str,',');
max = sizeof(result);
printf("Max is %d\n",max);
for(i=0; i<max; i++) {
printf("%s\n",result[i]);
}
char * nums[3][4] = {"1","2","3","\n","4","5","6","\n","7","8","9","\n"};
for (i=0,j=0; i < 3; i++) {
for (j=0; j < 4; j++) {
printf("%s",nums[i][j]);
}
}
return 0;
}
|
Output:
|
1,2,3,\n,4,5,6,\n,7,8,9,\n
Count is 11
Max is 4
1
2
3
\n
123
456
789
|
|