#include <stdio.h>
#include <stdint.h>
void split_string(const char *str, char delimiter, char tokens[10][20], uint8_t *count) {
int index = 0; //This variable is to traverse through each row array and to store the index of columns
//Traverse through the Array
while(*str){
//Case 1 :- When a Delimiter is found and the index is not in the first position
if(*str == delimiter){
tokens[*count][index] = '\0'; //To terminate the string
(*count)++; //Rows is increased to store a new word
index = 0; //To start from the first index and start to store
}
//Case 2 :- If the last index does not contain a delimiter
else if((*(str + 1) == '\0') && (*str != delimiter)){
tokens[*count][index] = *str; //To Store the value of current index
tokens[*count][index + 1] = '\0'; //To terminate the string
(*count)++; //Increment the count
}
//Case 3 :- If it is neither a delimitter nor a last index
else{
tokens[*count][index] = *str; //To Store the value of current index
index++; //To Increment the current index
}
//Finally Increment the str pointer to traverse through the array
*str++;
}
}
int main() {
char str[101];
char delimiter;
fgets(str, sizeof(str), stdin);
scanf(" %c", &delimiter);
// Remove newline
uint8_t i = 0;
while (str[i]) {
if (str[i] == '\n') { str[i] = '\0'; break; }
i++;
}
char tokens[10][20];
uint8_t count = 0;
split_string(str, delimiter, tokens, &count);
for (uint8_t i = 0; i < count; i++) {
printf("%s\n", tokens[i]);
}
return 0;
}
index
to track the position within each token (column in the 2D array).\0
.count
).index
to start a new token.\0
.index
to continue filling the token.
Input
cmd1,cmd2,cmd3 ,
Expected Output
cmd1 cmd2 cmd3