I have inherited a large code base and there is a utility function to split strings on :
char. I understand about 80% of how it works, I do not understand the *token = '\0';
line.
Any pointers are highly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TOKEN_SIZE 200
const char *splitter(const char *str, char delimiter, char *token) {
while (*str && (delimiter != *str)) {
*token++ = *str;
str++;
}
if (delimiter == *str)
str++;
*token = '\0'; // what is this line doing?
//how could the token be correct in the main() after setting it to null terminator
//here?
return str;
}
int main() {
char token[MAX_TOKEN_SIZE + 1];
const char *env = "/bin:/sbin:::/usr/bin";
while (*env) {
env = splitter(env, ':', token);
//if token is empty, set it to "./"
if ((token != NULL) && (token[0] == '\0')) {
strcpy(token, "./\0");
}
printf("%s\n", token) ;
}
return 0;
}
The output is correct:
/bin
/sbin
./
./
/usr/bin