LearnFrenzy
Sign in Take a free test

C Library Functions · Predict the Output · Question 6

strtok on "a,b,,c" – how many tokens? Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char csv[] = "red,green,,blue";
    int n = 0;
    for (char *t = strtok(csv, ","); t != NULL; t = strtok(NULL, ",")) {
        printf("[%s]", t);
        n++;
    }
    printf(" %d\n", n);
    return 0;
}
  • A [red][green][blue] 3 Correct
  • B [red][green][][blue] 4
  • C [red,green,,blue] 1
  • D [red][green] 2
Correct Answer: Option A

strtok treats a run of delimiters as one separator, so the empty field disappears. To keep empty fields, parse with strchr or strsep.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links