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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!