I split a string by
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main()
{
for (int i = 0; i < 1000; i++)
{
char *str, *delm;
str = "The first part/the second part/still in the second part"; // str comes from within the loop
delm = "/";
// The function block
size_t len = strlen(str);
char *ptr;
int pos;
ptr = strstr(str, delm);
if (ptr == NULL)
{
pos = -1;
}
else
{
pos = ptr - str;
}
if (pos > -1)
{
char first[pos + 1];
strncpy(first, str, pos);
first[pos] = 0;
char second[len - pos + 1];
strncpy(second, str + pos + 1, len - pos);
second[len - pos] = 0;
// end of the block
printf("%s - %s\n", first, second);
}
}
}
Since I often use this process, it is beneficial to define a function to make the code easy to read:
void split(const char *str, const char *delm, char *first, char *second){
// the code
}
In this case, I need to define the variables first and second dynamically via malloc and realloc since their sizes are not known outside the function. This may impact the performance (though the function may also do).
In general, I am curious if there is a trick for executing a function with output on the stack?