Split on Commas
Completed
Read a line of comma-separated values and print each value on its own line (trimmed of spaces), without strtok.
Input
One line.
Output
One value per line.
Example
Input
red, green ,blue
Output
red green blue
Editor
C
Hints
Remember where the current value starts; print it when you reach a comma or the end.
Solution explanation
A (start, end) pair of positions describes a piece of a string without copying it.
Show solution
#include <stdio.h>
#include <string.h>
void print_trimmed(char *s, int start, int end) {
while (start < end && s[start] == ' ') start++;
while (end > start && s[end - 1] == ' ') end--;
for (int i = start; i < end; i++) printf("%c", s[i]);
printf("\n");
}
int main() {
char s[300];
fgets(s, 300, stdin);
s[strcspn(s, "\n")] = '\0';
int start = 0;
int i = 0;
while (s[i] != '\0') {
if (s[i] == ',') {
print_trimmed(s, start, i);
start = i + 1;
}
i++;
}
print_trimmed(s, start, i);
return 0;
}