Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.623218'
Strings: Longest Word in a Sentence
Strings: Longest Word in a Sentence
Create a C program that reads a sentence from the user and finds the longest word in the sentence. The program should display the longest word as the output.
Library functions can be used!
Hint: Use character arrays (char arrays) to store the sentence and individual words.
Prompt the user to enter a sentence.
Tokenize the sentence into individual words (words are separated by spaces).
Find the longest word in the sentence.
Display the longest word as the output.
strtok(char str[], char delim[]) if a function that gives back a string that ends with the next delim[] (or EoS) (here " " string that contains a space), gives back NULL, if there is no more delim[] string found, strtok(NULL," "); will give you the next token
Solution
#include
#include
int main() {
char sentence[200];
char longestWord[50] = "";
int longestLength = 0;
printf("Enter a sentence: ");
scanf("%199[^\n]", sentence);
// Tokenize the sentence into individual words
char* token = strtok(sentence, " ");
while (token != NULL) {
// Check if the current word is longer than the longest word found so far
int length = strlen(token);
if (length > longestLength) {
longestLength = length;
strcpy(longestWord, token);
}
token = strtok(NULL, " ");
}
printf("Longest word: %s\n", longestWord);
return 0;
}
Explanation
The program defines a character array (char array) sentence to store the input sentence, a character array longestWord to store the longest word, and an integer variable longestLength to keep track of the length of the longest word. The user is prompted to enter a sentence using printf() and scanf(). The %199[^\n] format specifier is used to read the entire line until a newline character (\n) is encountered, allowing the program to read a sentence with spaces. The program uses strtok() function from the string.h library to tokenize the sentence into individual words. The delimiter used is a space " ", which separates words in the sentence. The program uses a loop to traverse through each word in the sentence. Inside the loop, the program checks the length of the current word using strlen() function from the string.h library. If the length of the current word is greater than the length of the longest word found so far, it updates the longestWord and longestLength variables accordingly.