LearnFrenzy
Sign in Take a free test

C Library Functions · Library Function Programs · Question 4

Count words and find the longest with strtok in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Split a sentence into words with strtok (spaces and punctuation as delimiters), count them and print the longest word.

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

int main(void) {
    char text[] = "Practice daily, and programming becomes natural.";
    char longest[32] = "";
    int count = 0;
    for (char *w = strtok(text, " ,.!?"); w != NULL; w = strtok(NULL, " ,.!?")) {
        count++;
        if (strlen(w) > strlen(longest))
            snprintf(longest, sizeof longest, "%s", w);
    }
    printf("%d words, longest: %s (%zu letters)\n", count, longest, strlen(longest));
    return 0;
}

Output Verified by compiling and running

6 words, longest: programming (11 letters)

strtok accepts a set of delimiter characters, so commas and full stops never become part of a word. The text must be a writable array because strtok modifies it.

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